package com.hsmw.api.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dyvmsapi20170525.models.SingleCallByVoiceResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.config.jwt.LoginUser;
import com.hsmw.api.controller.pub.GenerateIDUtils;
import com.hsmw.api.controller.pub.TencentPushUtils;
import com.hsmw.api.controller.pub.WebSocket;
import com.hsmw.api.mapper.*;
import com.hsmw.api.task.Sample;
import com.hsmw.api.utils.GaoDeInfoUtils;
import com.hsmw.api.utils.YLWUtils;
import com.hsmw.api.vo.*;
import com.hsmw.api.vo.DriverOrderInfoVO;
import com.hsmw.common.base.BasePage;
import com.hsmw.common.base.BaseService;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.*;
import com.hsmw.api.utils.CommonUtils;
import com.htn.common.core.util.SendSmsUtil;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import com.hsmw.domain.vo.*;
import com.hsmw.domain.vo.DriverCountVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * @author WD
 */
@Slf4j
@Service
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class HsmwOrderService extends BaseService<HsmwOrderMapper, HsmwOrder> {

    @Autowired
    private HsmwConcretePlantInfoMapper hsmwConcretePlantInfoMapper;
    @Autowired
    private HsmwOrderMapper hsmwOrderMapper;
    @Autowired
    private HsmwOrderForceManRelationService hsmwOrderForceManRelationService;
    @Autowired
    private HsmwOrderVehicleRelationService hsmwOrderVehicleRelationService;
    @Autowired
    private HsmwOrderVehicleRequestService hsmwOrderVehicleRequestService;
    @Autowired
    private HsmwDictDataService hsmwDictDataService;
    @Autowired
    private HsmwUserMapper hsmwUserMapper;
    @Autowired
    private CurrentHsmwUserUtils currentHsmwUserUtils;
    @Autowired
    private HsmwVehicleService hsmwVehicleService;
    @Autowired
    private HsmwVehicleMapper hsmwVehicleMapper;
    @Autowired
    private HsmwDriverNewsService hsmwDriverNewsService;
    @Autowired
    private HsmwUserDriverMapper hsmwUserDriverMapper;
    @Autowired
    private HsmwOrderForceManRelationMapper hsmwOrderForceManRelationMapper;
    @Autowired
    private HsmwUserDriverService hsmwUserDriverService;
    @Autowired
    private HsmwOrderVehicleRequestMapper hsmwOrderVehicleRequestMapper;
    @Autowired
    private HsmwItemService hsmwItemService;
    @Autowired
    private HsmwConstructionUnitService hsmwConstructionUnitService;

    @Autowired
    private HsmwOrderVehicleRelationMapper hsmwOrderVehicleRelationMapper;
    @Autowired
    private HsmwOrderDistributeInfoService hsmwOrderDistributeInfoService;
    @Autowired
    private HsmwPictureService hsmwPictureService;

    @Autowired
    private HsmwReportMapper hsmwReportMapper;


    @Autowired
    private HsmwReportService hsmwReportService;

    @Autowired
    private HsmwOrderService hsmwOrderService;

    @Autowired
    private WebSocket webSocket;

    @Autowired
    private HsmwForcemanMedalMapper hsmwForcemanMedalMapper;

    @Autowired
    private HsmwConstructionPositionService hsmwConstructionPositionService;


    @Autowired
    private HsmwConcreteInfoService hsmwConcreteInfoService;


    @Autowired
    private HsmwConcreteInfoMapper hsmwConcreteInfoMapper;


    @Autowired
    private HsmwConcreteOperateMapper hsmwConcreteOperateMapper;


    @Autowired
    private HsmwConcreteOperateService hsmwConcreteOperateService;


    @Autowired
    private HsmwConcreteOperateRecordService hsmwConcreteOperateRecordService;


    @Autowired
    private HsmwPumpOperateRecordService hsmwPumpOperateRecordService;


    @Autowired
    private HsmwForcemanEvaluateService hsmwForcemanEvaluateService;


    @Autowired
    private HsmwForcemanAddressService hsmwForcemanAddressService;


    @Autowired
    private HsmwVolumeRecordService hsmwVolumeRecordService;


    @Autowired
    private HsmwRequestVehicleService hsmwRequestVehicleService;

    @Autowired
    private HsmwDriverUserService hsmwDriverUserService;

    @Autowired
    private HsmwHtnUserService hsmwHtnUserService;

    @Autowired
    private HsmwConcreteUserMapper hsmwConcreteUserMapper;

    @Autowired
    private HsmwDriverUserMapper hsmwDriverUserMapper;

    @Autowired
    private HsmwOrderRemarkMapper hsmwOrderRemarkMapper;

    @Autowired
    private HsmwDictTypeService hsmwDictTypeService;


    @Autowired
    private HsmwLeasingCompanyService hsmwLeasingCompanyService;

    @Autowired
    private HsmwReceiveOrderPriceMapper hsmwReceiveOrderPriceMapper;

    @Autowired
    private HsmwCorporationCompanyMapper hsmwCorporationCompanyMapper;

    @Autowired
    private HsmwMonitorDriverMessageMapper hsmwMonitorDriverMessageMapper;

    @Autowired
    private HsmwHtnUserMapper hsmwHtnUserMapper;

    @Autowired
    private HsmwRunSprintRecordService hsmwRunSprintRecordService;

    @Autowired
    private HsmwDriverCancelOrderRecordMapper hsmwDriverCancelOrderRecordMapper;

    @Autowired
    private HsmwOrderBalanceMapper hsmwOrderBalanceMapper;

    @Autowired
    private HsmwBanDriverService hsmwBanDriverService;

    @Autowired
    private HsmwScoringRecordMapper hsmwScoringRecordMapper;

    @Autowired
    private HsmwDispatchOrderRemarkMapper  hsmwDispatchOrderRemarkMapper;


    @Value(value = "${sms.appKey}")
    private String appKey;
    @Value(value = "${sms.channel}")
    private String channel;
    @Value(value = "${sms.smsSign}")
    private String smsSign;
    @Value(value = "${sms.appId}")
    private int appId;
    @Value(value = "${sms.orderTemplateId}")
    private int orderTemplateId;

    @Value(value = "${sms.driverTemplateId}")
    private int driverTemplateId;

    @Value(value = "${sms.orderTimeoutNoticeBiz}")
    private int orderTimeoutNoticeBiz;

    @Value(value = "${sms.textOrderTimeOut}")
    private int textOrderTimeOut;

    @Value(value = "${sms.newConcreteOrder}")
    private int newConcreteOrder;

    @Value(value = "${sms.htnUpdateTime}")
    private int htnUpdateTime;


    @Value(value = "${sms.foremanCreateOrderSms}")
    private int foremanCreateOrderSms;


    @Value(value = "${sms.projectManCreateOrderSms}")
    private int projectManCreateOrderSms;

    @Value(value = "${sms.driverOrderCanceled}")
    private int driverOrderCanceled;


    @Value(value = "${sms.driverOrderUnArrivedCanceled}")
    private int driverOrderUnArrivedCanceled;


    final static String voiceCode = "0e7fe15a-5f6a-412f-8172-9f324d8c3bce.wav";

    final static Long queryTime = 3L;

    static {
        System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2,SSLv3");
    }


    public List<HsmwOrder> selectOrderListByItemId(LambdaQueryWrapper<HsmwOrder> lambdaQueryWrapper) {
        lambdaQueryWrapper.orderByDesc(HsmwOrder::getCreateTime);
        return hsmwOrderMapper.selectList(lambdaQueryWrapper);
    }

    //比较并更新
    public boolean compareAndUpdate(HsmwOrder order) {
        HsmwOrder hsmwOrder = hsmwOrderMapper.selectById(order.getId());
        if (order.getVersion() != hsmwOrder.getVersion()) {
            return false;
        }
        order.setVersion(order.getVersion() + 1);
        hsmwOrderMapper.updateById(order);
        return true;

    }


    /**
     * 工长端进行订单的创建与修改
     */
    @Transactional
    public DataResponse saveConcreteOrderInfo(HsmwOrderVO hsmwOrder, String foremanType) {
        HsmwHtnUser hsmwUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
        List<HsmwConstructionPosition> constructionPositions = hsmwOrder.getHsmwConstructionPositionList();
        double expectVolume = 0.0;
        for(HsmwConstructionPosition position:constructionPositions){
            expectVolume += new Double(position.getExpectVolumeSum());
        }
        boolean openFlag=false;
        BigDecimal availableLimit =  new BigDecimal("0.0");
        if(HtnUserTypeEnum.COMPANY.getValue().equals(hsmwUser.getType())){
            HsmwLeasingCompany company =hsmwLeasingCompanyService.getById(hsmwUser.getOwnCompanyId());
            openFlag=company.isOpenFlag();
            hsmwOrder.setOpenFlag(openFlag);
            availableLimit = company.getAvailableLimit();
        }
        if(HtnUserTypeEnum.CONCRETE.getValue().equals(hsmwUser.getType())){
            HsmwConcretePlantInfo company =hsmwConcretePlantInfoMapper.selectById(hsmwUser.getOwnCompanyId());
            openFlag=company.isOpenFlag();
            hsmwOrder.setOpenFlag(openFlag);
            availableLimit = company.getAvailableLimit();
        }
        if(HtnUserTypeEnum.FOREMAN.getValue().equals(hsmwUser.getType())){
            hsmwOrder.setIfSelfChoose(CommonConstants.NO);
            HsmwItem item = hsmwItemService.getHsmwItemById(hsmwOrder.getItemId());
            HsmwHtnUser itemCreateUser =hsmwHtnUserMapper.selectById(item.getCreateUser());
            if(StringUtils.isNotNull(itemCreateUser)){
                if(HtnUserTypeEnum.COMPANY.getValue().equals(itemCreateUser.getType())){
                    HsmwLeasingCompany company =hsmwLeasingCompanyService.getById(itemCreateUser.getOwnCompanyId());
                    openFlag=company.isOpenFlag();
                }
                if(HtnUserTypeEnum.CONCRETE.getValue().equals(itemCreateUser.getType())){
                    HsmwConcretePlantInfo company =hsmwConcretePlantInfoMapper.selectById(itemCreateUser.getOwnCompanyId());
                    openFlag=company.isOpenFlag();
                }
                hsmwOrder.setOpenFlag(openFlag);
            }
        }
        hsmwOrder.setIfSelfChoose(CommonConstants.NO);
        //如果开通了平台叫泵 并且 指定下单的车辆中有一个是外租泵 那么就计算额度是否足够
        if(openFlag){
            //指定车辆列表
            List<VehicleInfoVO> selectedVehicles = hsmwOrder.getSelectedVehicles();
            boolean outFlag = false;
            List<HsmwOrderVehicleRequest> requestList = new ArrayList<>();
            for(VehicleInfoVO vehicleInfoVO :selectedVehicles){
                if(CommonConstants.YES.equals(vehicleInfoVO.getOutsideLeasingFlag())){
                    outFlag = true;
                    break;
                }
            }
            for(VehicleInfoVO vehicleInfoVO :selectedVehicles){
                HsmwOrderVehicleRequest request =  new HsmwOrderVehicleRequest();
                request.setVehicleType(vehicleInfoVO.getVehicleType());
                request.setVehicleModel(vehicleInfoVO.getVehicleModel());
                requestList.add(request);
            }
            if(outFlag){
                BigDecimal settlePrice = getMaxPrice(requestList,hsmwUser);
                Double settlePriceDouble = settlePrice.doubleValue();
                Double availableLimitDouble =0.00;
                if(StringUtils.isNotNull(availableLimit)){
                    availableLimitDouble=availableLimit.doubleValue();
                }
                //每次下单时判断当前订单的预计方量是否小于{剩余额度-（单价*100）}/单价
                //如果余额不足就返回提示。
                if (0.00!=settlePriceDouble && (availableLimitDouble- (settlePriceDouble*100))/settlePriceDouble <expectVolume){
                    HashMap res = new HashMap();
                    res.put("code",111);
                    return new DataResponse(CommonConstants.ResponseStatus.BALANCE_NOT_ENOUGH,res);
                }
            }
        }
        /*
        //只有平台叫泵 在开通了并开启了以后 才需要计算 。首先计算出 所选择的泵车的类型和型号所对应的价格最高者
        List<HsmwOrderVehicleRequest> requestList = hsmwOrder.getVehicleRequestList();
        BigDecimal settlePrice = getMaxPrice(requestList,hsmwUser);
        Double settlePriceDouble = settlePrice.doubleValue();
        Double availableLimitDouble =0.00;
        if(StringUtils.isNotNull(availableLimit)){
            availableLimitDouble=availableLimit.doubleValue();
        }
        //每次下单时判断当前订单的预计方量是否小于{剩余额度-（单价*100）}/单价
        //如果余额不足就返回提示。
        if(openFlag){
            if (0.00!=settlePriceDouble && (availableLimitDouble- (settlePriceDouble*100))/settlePriceDouble <expectVolume){
                HashMap res = new HashMap();
                res.put("code",111);
                return new DataResponse(CommonConstants.ResponseStatus.BALANCE_NOT_ENOUGH,res);
            }
        }*/
        hsmwOrder.setExpectVolume(expectVolume+"");
        if(StringUtils.isNotBlank(hsmwOrder.getCreateUser())){
            hsmwOrder.setForemanUserId(hsmwOrder.getCreateUser());
        }else {
            hsmwOrder.setForemanUserId(hsmwUser.getId());
        }
        String orderId = CommonUtils.generateId(hsmwOrder);
        hsmwOrder.setId(orderId);
        String itemId = "";
        if(StringUtils.isNotBlank(hsmwOrder.getItemId())){
            itemId = hsmwOrder.getItemId();
        }else{
            itemId = hsmwUser.getItemId();
        }
        HsmwItem hsmwItem = hsmwItemService.getHsmwItemById(itemId);
        hsmwOrder.setOrderStatus(OrderStatusEnum.UNRECEIVED.getValue());
        //保存信息
        hsmwOrder = saveOrderInfo(hsmwOrder, hsmwUser, hsmwItem);

        HsmwForcemanMedal hsmwForcemanMedal = hsmwForcemanMedalMapper.selectOne(new LambdaQueryWrapper<HsmwForcemanMedal>().eq(HsmwForcemanMedal::getUserId, hsmwUser.getId()));
        if (null != hsmwForcemanMedal) {
            long l = new Double(hsmwOrder.getExpectVolume()).longValue();
            hsmwForcemanMedal.setVolume(hsmwForcemanMedal.getVolume() + l);
            hsmwForcemanMedal.setFirstOrderSuc(hsmwForcemanMedal.getFirstOrderSuc() + 1L);
            hsmwForcemanMedalMapper.updateById(hsmwForcemanMedal);
        }else {
            long l = new Double(hsmwOrder.getExpectVolume()).longValue();
            HsmwForcemanMedal forcemanMedal = new HsmwForcemanMedal();
            forcemanMedal.setFirstOrderSuc(1L);
            forcemanMedal.setVolume(l);
            forcemanMedal.setUserId(hsmwUser.getId());
            hsmwForcemanMedalMapper.insert(forcemanMedal);
        }
        //保存施工部位信息
        List<HsmwConstructionPosition> positions = hsmwOrder.getHsmwConstructionPositionList();
        List<HsmwConcreteInfo> hsmwConcreteInfos = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(positions)) {
            positions.stream().forEach(hsmwConstructionPosition -> {
                String positionId = CommonUtils.generateId(hsmwConstructionPosition);
                hsmwConstructionPosition.setOrderId(orderId);
                hsmwConstructionPosition.setId(positionId);
                hsmwConstructionPosition.setCreateUser(hsmwUser.getId());
                AtomicReference<Double> expectVolumeSum = new AtomicReference<>(0.0);
                List<HsmwConcreteInfo> hsmwConcreteInfss = hsmwConstructionPosition.getHsmwConcreteInfos();
                if (CollectionUtil.isNotEmpty(hsmwConcreteInfss)) {
                    hsmwConcreteInfss.stream().forEach(hsmwConcreteInfo -> {
                        hsmwConcreteInfo.setCreateUser(hsmwUser.getId());
                        hsmwConcreteInfo.setPositionId(positionId);
                        hsmwConcreteInfos.add(hsmwConcreteInfo);
                        expectVolumeSum.updateAndGet(v -> new Double((double) (v + Double.parseDouble(hsmwConcreteInfo.getExpectVolume()))));
                    });
                }

            });
            hsmwConcreteInfoService.saveBatch(hsmwConcreteInfos);
            hsmwConstructionPositionService.saveBatch(positions);
        }
        //混天凝app下的泵车单 需要泵送
        if (hsmwOrder.getIfConcreteRequired().equals(CommonConstants.YES)  &&  !(hsmwUser.getType().equals(HtnUserTypeEnum.CONCRETE.getValue())&& hsmwOrder.getConcretePlantId().equals(hsmwUser.getOwnCompanyId())) ) {
            List<HsmwHtnUser> concreteUsers = hsmwHtnUserService.list(new LambdaQueryWrapper<HsmwHtnUser>()
                    .eq(HsmwHtnUser::getOwnCompanyId,hsmwOrder.getConcretePlantId())
                    .eq(HsmwHtnUser::getType,HtnUserTypeEnum.CONCRETE.getValue())
                    .eq(HsmwHtnUser::getRoleType,HtnUserRoleEnum.LEADING.getValue()));
            if(CollectionUtil.isNotEmpty(concreteUsers)){
                HsmwHtnUser user = concreteUsers.get(0);
                HsmwConcretePlantInfo hsmwConcretePlantInfo = hsmwConcretePlantInfoMapper.selectById(hsmwOrder.getConcretePlantId());
                //发送混凝土订单的云打印
                YLYNewOrderDTO newOrderDTO = new YLYNewOrderDTO();
                newOrderDTO.setMechineId(hsmwConcretePlantInfo.getMechineId());
                YLWUtils.sendNewOrder(newOrderDTO);

                String msg = "您有新的混凝土订单，请前往APP查看并同意或拒绝接单";
                TencentPushUtils.pushForeManMsg(msg,user.getUsername(),"");
                HsmwDriverNews news = new HsmwDriverNews();
                news.setMessage(msg);
                news.setUserId(user.getId());
                news.setAlreadyRead("0");
                hsmwDriverNewsService.save(news);

            }
        }
        //订单创建完以后 需要 给相应人员发短信
        StringBuilder message= new StringBuilder();
        message.append(hsmwOrder.getItemName()+"的");
        //公司用户 或者搅拌站用户
        if (HtnUserTypeEnum.COMPANY.getValue().equals(hsmwUser.getType()) || HtnUserTypeEnum.CONCRETE.getValue().equals(hsmwUser.getType())){
            if(HtnUserTypeEnum.COMPANY.getValue().equals(hsmwUser.getType())){
                message.append("公司");
                if(HtnUserRoleEnum.LEADING.getValue().equals(hsmwUser.getRoleType())){
                    message.append("负责人");
                }
                if(HtnUserRoleEnum.DISPATCH.getValue().equals(hsmwUser.getRoleType())){
                    message.append("调度");
                }
            }
            if(HtnUserTypeEnum.CONCRETE.getValue().equals(hsmwUser.getType())){
                message.append("搅拌站");
                if(HtnUserRoleEnum.LEADING.getValue().equals(hsmwUser.getRoleType())){
                    message.append("负责人");
                }
                if(HtnUserRoleEnum.DISPATCH.getValue().equals(hsmwUser.getRoleType())){
                    message.append("调度");
                }
            }

            message.append(hsmwUser.getName()+"下单成功，您可以进入查看订单信息");
            //查询出该公司 其他的人员 进行推送信息
            List<HsmwHtnUser> users = hsmwHtnUserService.list(new LambdaQueryWrapper<HsmwHtnUser>()
                    .eq(HsmwHtnUser::getType,hsmwUser.getType())
                    .eq(HsmwHtnUser::getOwnCompanyId,hsmwUser.getOwnCompanyId())
                    .ne(HsmwHtnUser::getId,hsmwUser.getId()));
            if(CollectionUtil.isNotEmpty(users)){
                for (HsmwHtnUser user :users){
                    TencentPushUtils.pushForeManMsg(message.toString(),user.getUsername(),"");

                    HsmwDriverNews news = new HsmwDriverNews();
                    news.setMessage(message.toString());
                    news.setUserId(user.getId());
                    news.setAlreadyRead("0");
                    hsmwDriverNewsService.save(news);


                }
            }
        }
        if(HtnUserTypeEnum.FOREMAN.getValue().equals(hsmwUser.getType())){
            if(CommonConstants.YES.equals(hsmwUser.getRoleType())){
                message.append("项目负责人");
            }
            if(CommonConstants.NO.equals(hsmwUser.getRoleType())){
                message.append("项目工长");
            }
            message.append(hsmwUser.getName()+"下单成功，您可以进入查看订单信息");
            HsmwItem item = hsmwItemService.getHsmwItemById(hsmwOrder.getItemId());
            //查询出该项目的泵送公司的 人员 进行推送信息
            List<HsmwHtnUser> users = hsmwHtnUserService.list(new LambdaQueryWrapper<HsmwHtnUser>()
                    .eq(HsmwHtnUser::getOwnCompanyId,item.getVehicleUnitId())
                    .eq(HsmwHtnUser::getEnabled,true));
            if(CollectionUtil.isNotEmpty(users)){
                for (HsmwHtnUser user :users){
                    TencentPushUtils.pushForeManMsg(message.toString(),user.getUsername(),"");
                    HsmwDriverNews news = new HsmwDriverNews();
                    news.setMessage(message.toString());
                    news.setUserId(user.getId());
                    news.setAlreadyRead("0");
                    hsmwDriverNewsService.save(news);
                }
            }
        }

        //订单创建完以后 需要泵送 则 进行派单
        ReturnVO returnVO = compulsoryDispatchOrder(hsmwOrder);
        HashMap result = new HashMap();
        result.put("openFlag",openFlag);
        result.put("message","创建成功");
        result.put("orderId",orderId);
        if(openFlag){
            if(CollectionUtil.isNotEmpty(returnVO.getRequestList())){
                result.put("vehicleEnough",0);
                if(HtnUserTypeEnum.FOREMAN.getValue().equals(hsmwUser.getType())){
                    HsmwItem item = hsmwItemService.getHsmwItemById(hsmwOrder.getItemId());
                    HsmwHtnUser itemCreator = hsmwHtnUserService.getHsmwUserById(item.getCreateUser());
                    if(StringUtils.isNotNull(itemCreator)){
                        //如果 项目的创建人不是空的 那么查询出来 该项目的创建人所在公司的负责人电话
                        List<HsmwHtnUser> users = hsmwHtnUserService.list(new LambdaQueryWrapper<HsmwHtnUser>()
                                .eq(HsmwHtnUser::getRoleType,CommonConstants.YES)
                                .eq(HsmwHtnUser::getOwnCompanyId,itemCreator.getOwnCompanyId()));
                        if(CollectionUtil.isNotEmpty(users)){
                            HsmwHtnUser userInfo = users.get(0);
                            WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
                            webSocketReturnVO.setOrderId(hsmwOrder.getId());
                            webSocketReturnVO.setPushType(PushTypeEnum.ENSURE_SELFCHOOSE.getValue());
                            webSocketReturnVO.setMessage("当前空闲车辆不能满足该订单，是否需要花费额度中的现金从平台叫车");
                            TencentPushUtils.htnPushInviteMsg("当前空闲车辆不能满足该订单，是否需要花费额度中的现金从平台叫车",
                                    userInfo.getUsername(),webSocketReturnVO);
                            String[] params = new String[]{hsmwOrder.getItemName(),hsmwUser.getName()+" "+hsmwUser.getUsername()};
                            if(HtnUserRoleEnum.LEADING.getValue().equals(hsmwUser.getRoleType())){
                                SendSmsUtil.sendSmsWithParam(appId, appKey, params, projectManCreateOrderSms, smsSign, userInfo.getUsername());
                            }else {
                                SendSmsUtil.sendSmsWithParam(appId, appKey, params, foremanCreateOrderSms, smsSign, userInfo.getUsername());
                            }
                        }
                    }
                }
            }else {
                result.put("vehicleEnough",1);
            }
        }
        return DataResponse.success(result);
    }
    public  BigDecimal getMaxPrice(List<HsmwOrderVehicleRequest> requestList,HsmwHtnUser user){
        BigDecimal resultPrice = new BigDecimal("17.00");
        List<HsmwReceiveOrderPrice> receiveOrderPrices = hsmwReceiveOrderPriceMapper.selectList(new LambdaQueryWrapper<HsmwReceiveOrderPrice>()
                .eq(HsmwReceiveOrderPrice::getCompanyId,user.getOwnCompanyId())
                .eq(HsmwReceiveOrderPrice::getSettleType,SettlementTypeEnum.PUMP_PRICE.getValue()));
        List<HsmwReceiveOrderPrice> exitsPrice =new ArrayList<>();
        for(HsmwReceiveOrderPrice price: receiveOrderPrices){
            for(HsmwOrderVehicleRequest request :requestList){
                if(request.getVehicleModel().equals(price.getVehicleModel()) && request.getVehicleType().equals(price.getVehicleType())){
                    exitsPrice.add(price);
                    continue;
                }
            }
        }
        if(CollectionUtil.isNotEmpty(exitsPrice)){
            sortObjectList(exitsPrice);
            resultPrice= exitsPrice.get(0).getSettlePrice();
        }
        return resultPrice;
    }

    private void sortObjectList(List<HsmwReceiveOrderPrice > listOut) {
        Collections.sort(listOut, new Comparator<HsmwReceiveOrderPrice>() {
            @Override
            public int compare(HsmwReceiveOrderPrice o1, HsmwReceiveOrderPrice o2) {
                return o1.getSettlePrice().compareTo(o2.getSettlePrice());//降序
            }
        });
    }



    public HashMap chooseReqInfo(List<HsmwOrderVehicleRequest> requestList) {
        HashMap result = new HashMap();
        for (HsmwOrderVehicleRequest request : requestList) {
            String key = request.getVehicleType() + " " + request.getVehicleModel();
            if (result.containsKey(key)) {
                int count = Integer.parseInt(result.get(key).toString());
                result.put(key, count + 1);
            } else {
                result.put(key, 1);
            }
        }
        return result;
    }


    public HsmwOrderVO saveOrderInfo(HsmwOrderVO hsmwOrder, HsmwHtnUser hsmwUser, HsmwItem hsmwItem) {
        String identifyNum = CommonUtils.generateOrderdentifyNum();
        LoginUser currentUser = currentHsmwUserUtils.getCurrentUserInfo();
        List<HsmwOrderRemark> orderRemarks = hsmwOrder.getOrderRemarks();
        if(CollectionUtil.isNotEmpty(orderRemarks)){
            orderRemarks.stream().forEach(orderRemark->{
                orderRemark.setOrderId(hsmwOrder.getId());
                orderRemark.setUserId(currentUser.getId());
                hsmwOrderRemarkMapper.insert(orderRemark);
            });
        }
        //如果是 自营的角色 项目ID是非空的 项目
        if (StringUtils.isBlank(hsmwOrder.getItemId())) {
            // HsmwItem
            hsmwOrder.setItemId(hsmwItem.getId());
            hsmwOrder.setItemName(hsmwItem.getName());
            hsmwOrder.setCreateName(currentUser.getName());
            hsmwOrder.setCreateUserTel(currentUser.getUsername());
        }
        hsmwOrder.setIdentityNum(identifyNum);
        if (StringUtils.isBlank(hsmwOrder.getCreateUserTel())) {
            hsmwOrder.setCreateUserTel(hsmwUser.getUsername());
        }
        hsmwOrder.setConstructionUnitName(hsmwItem.getConstructionUnitName());
        int reqCount = 0;
        if (StringUtils.isListNotNull(hsmwOrder.getVehicleRequestList())) {
            reqCount = hsmwOrder.getVehicleRequestList().size();
        }
        hsmwOrder.setReqCount(String.valueOf(reqCount));
        hsmwOrder.setOrderSn(RandomUtil.randomUUID());
        hsmwOrder.setCreateUser(currentUser.getId());
        if (StringUtils.isBlank(hsmwOrder.getLng()) && StringUtils.isBlank(hsmwOrder.getLat())) {
            hsmwOrder.setLng(hsmwItem.getLng());
            hsmwOrder.setLat(hsmwItem.getLat());
        }
        try {
            hsmwOrder.setCreateTime(LocalDateTime.now());
            //保存车辆信息
            this.save(hsmwOrder);
            HsmwPumpOperateRecord record = new HsmwPumpOperateRecord();
            record.setOrderId(hsmwOrder.getId());
            record.setName(hsmwUser.getName());
            record.setUserType("工长");
            record.setUsername(hsmwUser.getUsername());
            record.setOrderStatus(PumpOrderStatusEnum.UNRECEIVED.getValue());
            record.setOperContent("下单成功");
            hsmwPumpOperateRecordService.save(record);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //保存车辆需求信息
        try {
            //判断车辆需求信息是否为空， 如果不为空则
            if (CommonUtils.ifListNotNull(hsmwOrder.getVehicleRequestList())) {
                List<HsmwOrderVehicleRequest> vehicleRequestList = new ArrayList<>();
                for (HsmwOrderVehicleRequest vehicleRequest : hsmwOrder.getVehicleRequestList()) {
                    int  count  = vehicleRequest.getVehicleNumber();
                    vehicleRequest.setOrderId(hsmwOrder.getId());
                    vehicleRequest.setCreateUser(hsmwUser.getId());
                    vehicleRequest.setVersion(0);
                    vehicleRequest.setReachTime(hsmwOrder.getReachTime());
                    vehicleRequest.setVehicleNumber(1);//默认为1
                    vehicleRequest.setAppointOrder(CommonConstants.NO);
                    vehicleRequest.setYears(hsmwOrder.getYears());
                    vehicleRequest.setArmSegment(hsmwOrder.getArmSegment());
                    vehicleRequest.setOrderType(OrderTypeEnum.PUMP_ORDER.getValue());
                    vehicleRequest.setAxis(hsmwOrder.getAxis());
                    //vehicleRequest.setRequestStatus(RequestStatusEnum.UNRECEIVED.getValue());
                    vehicleRequest.setIfSelfChoose(hsmwOrder.getIfSelfChoose());
                    vehicleRequest.setOrderType(OrderTypeEnum.PUMP_ORDER.getValue());
                    //同一个车辆类型需要几个车就创建几个request 信息
                    for(int i=0;i<count;i++){

                        List<String> reqList= new ArrayList<>();
                        HsmwOrderVehicleRequest req = new HsmwOrderVehicleRequest();
                        BeanUtil.copyProperties(vehicleRequest,req);;
                        req.setCreateTime(LocalDateTime.now());
                        String reqId = CommonUtils.generateId(req);
                        while(true) {
                            if(reqList.contains(reqId)){
                                reqId = CommonUtils.generateId(req);
                            }else{
                                reqList.add(reqId);
                                break;
                            }
                        }
                        req.setId(reqId);
                        vehicleRequestList.add(req);
                    }
                }
                hsmwOrderVehicleRequestService.saveBatch(vehicleRequestList);
               // hsmwOrder.setVehicleRequestList(vehicleRequestList);
            }else{
                List<VehicleInfoVO> selectedVehicles = hsmwOrder.getSelectedVehicles();
                List<HsmwOrderVehicleRequest> vehicleRequestList = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(selectedVehicles)){
                    for(VehicleInfoVO vo :selectedVehicles){
                        HsmwVehicle vehicle = hsmwVehicleMapper.selectById(vo.getVehicleId());
                        HsmwOrderVehicleRequest req = new HsmwOrderVehicleRequest();
                        req.setReachTime(hsmwOrder.getReachTime());
                        req.setCreateUser(hsmwUser.getId());
                        req.setVersion(0);
                        req.setVehicleModel(vo.getVehicleModel());
                        req.setVehicleType(vo.getVehicleType());
                        req.setAppointOrder(CommonConstants.YES);
                        req.setAxis(vehicle.getAxis()+"");
                        req.setOrderType(OrderTypeEnum.PUMP_ORDER.getValue());
                        req.setArmSegment(vehicle.getArmSegment());
                        req.setYears(vehicle.getYears()+"");
                        req.setAppointVehicleId(vo.getVehicleId());
                        req.setOrderId(hsmwOrder.getId());
                        //req.setRequestStatus(RequestStatusEnum.UNRECEIVED.getValue());
                        req.setIfSelfChoose(hsmwOrder.getIfSelfChoose());
                        req.setOutsideLeasingFlag(vo.getOutsideLeasingFlag());
                        req.setOrderType(OrderTypeEnum.PUMP_ORDER.getValue());
                        vehicleRequestList.add(req);
                    }
                    hsmwOrderVehicleRequestService.saveBatch(vehicleRequestList);
                    //hsmwOrder.setVehicleRequestList(vehicleRequestList);
                }
            }
            //保存 混凝土订单
            if(CommonConstants.YES.equals(hsmwOrder.getIfConcreteRequired())){
                HsmwOrderVehicleRequest request = new HsmwOrderVehicleRequest();
                request.setOrderId(hsmwOrder.getId());
                request.setOrderType(OrderTypeEnum.CONCRETE_ORDER.getValue());
                request.setAppointOrder(CommonConstants.NO);
                request.setReachTime(hsmwOrder.getConcreteReachTime());
                request.setConcreteOrderStatus(ConcreteOrderStatusEnum.UNRECEIVED.getValue());
                request.setConcretePlantId(hsmwOrder.getConcretePlantId());
                request.setConcretePlantName(hsmwOrder.getConcretePlantName());
                request.setConcretePlantDistance(hsmwOrder.getConcretePlantDistance());
                request.setCreateUser(hsmwUser.getId());
                //request.set
                hsmwOrderVehicleRequestService.save(request);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (CollectionUtil.isNotEmpty(hsmwOrder.getPicList())) {
            List<HsmwPicture> pictures = new ArrayList<>();
            List<HashMap> picList = hsmwOrder.getPicList();
            if (null != picList && picList.size() > 0) {
                for (HashMap<String, String> pic : picList) {
                    HsmwPicture temp = new HsmwPicture();
                    temp.setPicPath(pic.get("picPath"));
                    temp.setPicRealPath(pic.get("realPath"));
                    temp.setOrderId(hsmwOrder.getId());
                    temp.setCreateTime(LocalDateTime.now());
                    temp.setPicType(PicTypeEnum.POSITION_PUMP.getValue());
                    pictures.add(temp);
                }
            }
            hsmwPictureService.saveBatch(pictures);
        }
        return hsmwOrder;
    }

    public HsmwConstructionPosition checkIfExists(List<HsmwConstructionPosition> hsmwConstructionPositionList, String positionName) {
        HsmwConstructionPosition checkedPosition = null;
        if (CollectionUtil.isNotEmpty(hsmwConstructionPositionList)) {
            for (HsmwConstructionPosition position : hsmwConstructionPositionList) {
                if (position.getPosition().equals(positionName)) {
                    checkedPosition = position;
                    break;
                }
            }
        }
        return checkedPosition;
    }


    /**
     * 强制派订单
     *
     * @param order
     * @return
     */
    public ReturnVO compulsoryDispatchOrder(HsmwOrderVO order) {
        ReturnVO returnVO = new ReturnVO();
        LoginUser user = currentHsmwUserUtils.getCurrentUserInfo();
        List<HsmwOrderVehicleRequest> undispatchRequest = new ArrayList<>();
        //强制 派单 ==== 首选查询出来 该订单所有的需求信息
        List<HsmwOrderVehicleRequest> requestList =hsmwOrderVehicleRequestMapper.selectList(new LambdaQueryWrapper<HsmwOrderVehicleRequest>()
                .eq(HsmwOrderVehicleRequest::getOrderId,order.getId())
                .eq(HsmwOrderVehicleRequest::getOrderType,OrderTypeEnum.PUMP_ORDER.getValue()));
        //分别对每一个需求进行派单
        requestList.stream().forEach(hsmwOrderVehicleRequest -> {
            //如果是 指定司机的订单
            if(CommonConstants.YES.equals(hsmwOrderVehicleRequest.getAppointOrder()) && StringUtils.isNotBlank(hsmwOrderVehicleRequest.getAppointVehicleId())){
                HsmwVehicle vehicle = hsmwVehicleMapper.selectById(hsmwOrderVehicleRequest.getAppointVehicleId());
                if(CommonConstants.VEHICLE_FREE.equals(vehicle.getWorkStatus())){
                    //如果hsmwOrderVehicleRequest 更新成功 那么直接进行子订单和司机相关的操作
                    if (hsmwOrderVehicleRelationService.checkIfVehicleWorking(hsmwOrderVehicleRequest.getAppointVehicleId())) {
                        //如果是指定车辆的下单 那么 车上的司机 空闲中和接单中的司机 必须大于0 最小是1
                        List<HsmwUserDriver> hsmwUserDriverList = hsmwUserDriverService.selectAvaliableList(vehicle.getId());
                        if(CollectionUtil.isNotEmpty(hsmwUserDriverList)){
                            //创建子订单信息
                            HsmwOrderVehicleRelation hsmwOrderVehicleRelation = new HsmwOrderVehicleRelation();
                            String relationId = CommonUtils.generateId(hsmwOrderVehicleRelation);
                            hsmwOrderVehicleRelation.setVehicleId(hsmwOrderVehicleRequest.getAppointVehicleId());
                            //hsmwOrderVehicleRelation.setDriverName(checkedDriverSortVO.);
                            hsmwOrderVehicleRelation.setOrderStatus(ChildOrderStatusEnum.RECEIVED.getValue());
                            hsmwOrderVehicleRelation.setOrderId(order.getId());
                            HsmwVehicle hsmwVehicle =vehicle;
                            hsmwOrderVehicleRelation.setImeiNum(hsmwVehicle.getImeiNum());
                            hsmwOrderVehicleRelation.setVehicleNum(hsmwVehicle.getVehiclePlate());
                            hsmwOrderVehicleRelation.setVehicleType(hsmwVehicle.getVehicleType());
                            hsmwOrderVehicleRelation.setVehicleModel(hsmwVehicle.getVehicleModel());
                            hsmwOrderVehicleRelation.setOrderVehicleRequestId(hsmwOrderVehicleRequest.getId());
                            //hsmwOrderVehicleRelation.setReachTime(hsmwOrderVehicleRequest.getCreateTime());
                            hsmwOrderVehicleRelation.setExpectVolume(hsmwOrderVehicleRequest.getExpectVolume());
                            hsmwOrderVehicleRelation.setAcceptOrderTime(LocalDateTime.now());
                            hsmwOrderVehicleRelation.setId(relationId);
                            if(StringUtils.isNotBlank(hsmwOrderVehicleRequest.getOutsideLeasingFlag()) && CommonConstants.YES.equals(hsmwOrderVehicleRequest.getOutsideLeasingFlag())){
                                hsmwOrderVehicleRelation.setOutsideLeasingFlag(CommonConstants.YES);
                            }else {
                                hsmwOrderVehicleRelation.setOutsideLeasingFlag(CommonConstants.NO);
                            }
                            hsmwOrderVehicleRequest.setRequestStatus(RequestStatusEnum.RECEIVED.getValue());

                            //插入数据前 判断数据是否已经改变。
                            if (hsmwOrderVehicleRequestService.compareAndUpdate(hsmwOrderVehicleRequest)) {
                                hsmwOrderVehicleRelationService.save(hsmwOrderVehicleRelation);
                                HsmwPumpOperateRecord record1 = new HsmwPumpOperateRecord();
                                record1.setOrderId(order.getId());
                                record1.setName(hsmwVehicle.getVehiclePlate());
                                record1.setUserType("");
                                record1.setCreateTime(LocalDateTime.now());
                                record1.setUsername(user.getUsername());
                                record1.setOrderStatus(PumpOrderStatusEnum.RECEIVED.getValue());
                                record1.setOperContent("接单 接单车辆为" + hsmwVehicle.getVehiclePlate());
                                hsmwPumpOperateRecordService.save(record1);
                                //针对筛选后的可以派单司机进行派单
                                ///接单中的司机进行推送
                                if (CollectionUtil.isNotEmpty(hsmwUserDriverList)) {
                                    for (HsmwUserDriver hsmwUserDriver : hsmwUserDriverList) {
                                        String userId1 = hsmwUserDriver.getUserId();
                                        HsmwDriverUser hsmwUsers = hsmwDriverUserMapper.selectById(userId1);
                                        if (hsmwUsers != null) {
                                            TencentPushUtils.pushMsg("系统已为您指派订单，请尽快前往APP查看，确认出发时间，以免延误工作！", hsmwUsers.getUsername(), "order_status_2");
                                            String msg = "系统已为您指派订单，请尽快前往APP查看，确认出发时间，以免延误工作！";
                                            SendSmsUtil.sendDriverSmsCode(appId, appKey, msg, orderTimeoutNoticeBiz, smsSign, hsmwUsers.getUsername());
                                            SendSmsUtil.sendBizOrderForceSms(appId, appKey, hsmwUsers.getName(), hsmwUsers.getUsername(), textOrderTimeOut, smsSign, "13520391225");
                                            try {
                                                SingleCallByVoiceResponse singleCallByVoiceResponse = Sample.SingleCallByVoice(Sample.createDyvmsapiClient(), hsmwUsers.getUsername(), voiceCode);
                                                Sample.QueryCallDetailByCallId(Sample.createDyvmsapiClient(), singleCallByVoiceResponse.body.callId, queryTime);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                }
                                //司机指派成功 则 将 司机状态改为 工作中
                                if (CollectionUtil.isNotEmpty(hsmwUserDriverList)) {
                                    hsmwUserDriverList.stream().forEach(hsmwUserDriver -> {
                                        hsmwUserDriver.setWorkStatus(CommonConstants.DRIVER_WORK);
                                    });
                                }
                                hsmwUserDriverService.updateBatchById(hsmwUserDriverList);
                                //司机抢单成功 则 将 司机状态改为  工作中
                                hsmwVehicle.setWorkStatus(CommonConstants.DRIVER_WORK);
                                hsmwVehicleService.updateById(hsmwVehicle);
                            }
                        }
                    }
                }
            }else {
                //如果不是指定车辆的下单 则走正常的下单流程。
                java. time.Duration duration = java.time.Duration.between(LocalDateTime.now(),  hsmwOrderVehicleRequest.getReachTime());
                //自营车辆的派单vo
                List<DriverUserSortVo> selfrunUserSortVos = new ArrayList<>();
                //合作公司的派单VO
                List<DriverUserSortVo> corperateDriverUserSortVos = new ArrayList<>();
                //平台的其他的公司的派单VO
                List<DriverUserSortVo> platformDriverUserSortVos = new ArrayList<>();
                //选中的司机信息
                DriverUserSortVo checkedDriverSortVO = null;

                //自营车辆的司机列表
                List<HsmwVehicle> selfrunVehicles = new ArrayList<>();
                //合作公司的司机列表
                List<HsmwVehicle> corperateVehicles = new ArrayList<>();
                //平台的其他的公司的司机列表
                List<HsmwVehicle> platformVehicles = new ArrayList<>();

                HsmwHtnUser createUser = hsmwHtnUserMapper.selectById(order.getCreateUser());
                //如果是公司用户 那么直接查询本公司的车辆作为自营车辆
                String selfrunCompanyId ="";
                if(HtnUserTypeEnum.COMPANY.getValue().equals(createUser.getType())){
                    selfrunCompanyId= createUser.getOwnCompanyId();
                }
                //如果是搅拌站用户  则查询自营合作公司的Id
                if(HtnUserTypeEnum.CONCRETE.getValue().equals(createUser.getType())){
                    List<HsmwCorporationCompany> corporationCompanies = hsmwCorporationCompanyMapper.selectList(new LambdaQueryWrapper<HsmwCorporationCompany>()
                            .eq(HsmwCorporationCompany::getConcretePlantId,createUser.getOwnCompanyId())
                            .eq(HsmwCorporationCompany::getCorperateType, CorperateTypeEnum.SELFRUN.getValue()));
                    if(CollectionUtil.isNotEmpty(corporationCompanies)){
                        selfrunCompanyId= corporationCompanies.get(0).getCorperateCompanyId();
                    }
                }
                //如果下单人员是 工长或者项目的负责人
                //查询该项目绑定的泵送公司
                String itemCreateUserCompanyId=null;
                HsmwHtnUser itemCreator =null;
                if(HtnUserTypeEnum.FOREMAN.getValue().equals(createUser.getType())){
                    HsmwItem item = hsmwItemService.getHsmwItemById(order.getItemId());
                    itemCreator = hsmwHtnUserService.getHsmwUserById(item.getCreateUser());
                    itemCreateUserCompanyId=itemCreator.getOwnCompanyId();
                    if(StringUtils.isNotNull(itemCreator)){
                        if(HtnUserTypeEnum.COMPANY.getValue().equals(itemCreator.getType())){
                            selfrunCompanyId= itemCreator.getOwnCompanyId();
                        }
                        //如果是搅拌站用户  则查询自营合作公司的Id
                        if(HtnUserTypeEnum.CONCRETE.getValue().equals(itemCreator.getType())){
                            List<HsmwCorporationCompany> corporationCompanies = hsmwCorporationCompanyMapper.selectList(
                                    new LambdaQueryWrapper<HsmwCorporationCompany>()
                                    .eq(HsmwCorporationCompany::getConcretePlantId,itemCreator.getOwnCompanyId())
                                    .eq(HsmwCorporationCompany::getCorperateType, CorperateTypeEnum.SELFRUN.getValue()));
                            if(CollectionUtil.isNotEmpty(corporationCompanies)){
                                selfrunCompanyId= corporationCompanies.get(0).getCorperateCompanyId();
                            }
                        }
                    }
                }
                //当指定车辆的ID不为空的时候
                if(StringUtils.isNotBlank(selfrunCompanyId)){
                    hsmwOrderVehicleRequest.setLeasingCompanyId(selfrunCompanyId);
                    selfrunVehicles = hsmwOrderService.getVehicleListByRequestId(hsmwOrderVehicleRequest,"1",createUser,null,itemCreator);
                }
                //租赁公司和搅拌站查询合作的公司的车辆
                corperateVehicles = hsmwOrderService.getVehicleListByRequestId(  hsmwOrderVehicleRequest,"2",createUser,itemCreateUserCompanyId,itemCreator);

                // 查询平台的车辆 的车辆 默认不派平台车辆
                //只有开启了平台叫泵的才会查询平台车辆
             /*   if(CommonConstants.YES.equals(order.getIfSelfChoose()) || HtnUserTypeEnum.FOREMAN.getValue().equals(createUser.getType())){
                if(CommonConstants.YES.equals(order.getIfSelfChoose())){
                    platformVehicles = hsmwOrderService.getVehicleListByRequestId(hsmwOrderVehicleRequest,"3",createUser,itemCreateUserCompanyId,itemCreator);
                }
*/

                //筛选 查询出来的自营车辆
                if(StringUtils.isListNotNull(selfrunVehicles)) {
                    String imeiStrs = "";
                    String vehicleIds = "";
                    for (HsmwVehicle vehicle : selfrunVehicles) {
                        if (StringUtils.isNotBlank(vehicle.getImeiNum()) || StringUtils.isNotBlank(vehicle.getIdentifyingCode())) {
                            imeiStrs += ("," + vehicle.getImeiNum());
                            vehicleIds += ("," + vehicle.getIdentifyingCode());
                        }
                    }
                    //查询车辆是否能到
                    List<GpsInfoEntity> gpsInfoEntities = new ArrayList<>();
                    if (StringUtils.isNotBlank(imeiStrs)) {
                        gpsInfoEntities = GaoDeInfoUtils.getVehicleGpsLocate(imeiStrs,vehicleIds);
                    }
                    List<GpsInfoEntity> finalGpsInfoEntities = gpsInfoEntities;

                    for (HsmwVehicle hsmwVehicle :selfrunVehicles) {
                        List<HsmwRequestVehicle> hsmwRequestVehicles = hsmwRequestVehicleService.
                                list(new LambdaQueryWrapper<HsmwRequestVehicle>()
                                        .eq(HsmwRequestVehicle::getVehilceId, hsmwVehicle.getId()).
                                                eq(HsmwRequestVehicle::getForemanUserId, order.getItemId()));
                        if (CollectionUtil.isNotEmpty(hsmwRequestVehicles)) {
                            continue;
                        }

                        // 查询接单中的司机 信息 如果没有接单中的司机那么 就不会进行派单
                        List<HsmwUserDriver> hsmwUserDrivers = hsmwUserDriverService.selectAvaliableList(hsmwVehicle.getId());
                        if(CollectionUtil.isEmpty(hsmwUserDrivers)){
                            continue;
                        }
                        String vehicleId = hsmwVehicle.getId();
                        DriverUserSortVo driverUserSortVo = new DriverUserSortVo();
                        driverUserSortVo.setVehicleId(vehicleId);
                        //查询距离时间
                        String vehicleLocalteInfo = null;
                        String destinationLocateInfo = order.getLng() + "," + order.getLat();
                        if (finalGpsInfoEntities.size() > 0) {
                            for (GpsInfoEntity entity : finalGpsInfoEntities) {
                                if (entity.getDeviceId().equals(hsmwVehicle.getImeiNum()) || StringUtils.equals(entity.getDeviceId(),hsmwVehicle.getIdentifyingCode())) {
                                    if (StringUtils.isNotBlank(entity.getGpsLat())) {
                                        vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                                    }
                                    break;
                                }
                            }
                            if (StringUtils.isBlank(vehicleLocalteInfo)) {
                                vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
                            }
                        }
                        if (StringUtils.isBlank(vehicleLocalteInfo)) {
                            vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
                        }
                        if (StringUtils.isNotBlank(vehicleLocalteInfo)) {
                            HashMap calculateParam = new HashMap();
                            calculateParam.put("origin", vehicleLocalteInfo);
                            calculateParam.put("destination", destinationLocateInfo);
                            Long durationTime = GaoDeInfoUtils.calculateDistanceTime(calculateParam);
                            long sconds = duration.toMillis() / 1000;
                            if ((float) sconds / 3600 < ((float) durationTime / 3600)) {
                                continue;
                            }
                            driverUserSortVo.setMobileLocate(durationTime);
                        } else {
                            //如果通过gps的获取的距离为空  那么  车不可用，直接将距离设置为无限大
                            driverUserSortVo.setMobileLocate(100000000000L);
                        }
                        HsmwUserDriver driver = hsmwUserDrivers.get(0);
                        //user 信息
                        String userId = driver.getUserId();
                        HsmwDriverUser hsmwUser = hsmwDriverUserMapper.selectById(userId);
                        driverUserSortVo.setDriverList(hsmwUserDrivers);
                        driverUserSortVo.setDriverId(driver.getId());
                        driverUserSortVo.setHsmwOrder(order);
                        driverUserSortVo.setHsmwVehicle(hsmwVehicle);
                        driverUserSortVo.setHsmwUser(hsmwUser);
                        driverUserSortVo.setScore(driver.getScore());
                        driverUserSortVo.setVehicleUnit(0);
                        selfrunUserSortVos.add(driverUserSortVo);
                    }
                }
                if(CollectionUtil.isNotEmpty(selfrunUserSortVos)){
                    selfrunUserSortVos = sortDriverUserSort(selfrunUserSortVos);
                    checkedDriverSortVO = selfrunUserSortVos.get(0);
                    checkedDriverSortVO.setVehicleOwnType(VehicleTypeEnum.SELFRUN.getValue());
                    returnVO.setVehicleEnough(true);
                }else {
                    returnVO.setVehicleEnough(false);
                    //筛选 查询出来的平台车辆
                    if(StringUtils.isListNotNull(corperateVehicles)) {
                        String imeiStrs = "";
                        String vehicleIds = "";
                        for (HsmwVehicle vehicle : corperateVehicles) {
                            if (StringUtils.isNotBlank(vehicle.getImeiNum())) {
                                imeiStrs += ("," + vehicle.getImeiNum());
                                vehicleIds += ("," + vehicle.getIdentifyingCode());
                            }
                        }
                        //查询车辆是否能到
                        List<GpsInfoEntity> gpsInfoEntities = new ArrayList<>();
                        if (StringUtils.isNotBlank(imeiStrs)) {
                            gpsInfoEntities = GaoDeInfoUtils.getVehicleGpsLocate(imeiStrs,vehicleIds);
                        }
                        List<GpsInfoEntity> finalGpsInfoEntities = gpsInfoEntities;

                        for (HsmwVehicle hsmwVehicle :corperateVehicles) {
                            List<HsmwRequestVehicle> hsmwRequestVehicles = hsmwRequestVehicleService.
                                    list(new LambdaQueryWrapper<HsmwRequestVehicle>()
                                            .eq(HsmwRequestVehicle::getVehilceId, hsmwVehicle.getId()).
                                                    eq(HsmwRequestVehicle::getForemanUserId, order.getItemId()));
                            if (CollectionUtil.isNotEmpty(hsmwRequestVehicles)) {
                                continue;
                            }
                            // 查询接单中的司机 信息 如果没有接单中的司机那么 就不会进行派单
                            List<HsmwUserDriver> hsmwUserDrivers = hsmwUserDriverService.selectAvaliableList(hsmwVehicle.getId());
                            if(CollectionUtil.isEmpty(hsmwUserDrivers)){
                                continue;
                            }
                            String vehicleId = hsmwVehicle.getId();
                            DriverUserSortVo driverUserSortVo = new DriverUserSortVo();
                            driverUserSortVo.setVehicleId(vehicleId);
                            //查询距离时间
                            String vehicleLocalteInfo = null;
                            String destinationLocateInfo = order.getLng() + "," + order.getLat();
                            if (finalGpsInfoEntities.size() > 0) {
                                for (GpsInfoEntity entity : finalGpsInfoEntities) {
                                    if (entity.getDeviceId().equals(hsmwVehicle.getImeiNum()) || StringUtils.equals(entity.getDeviceId(),hsmwVehicle.getIdentifyingCode())) {
                                        if (StringUtils.isNotBlank(entity.getGpsLat())) {
                                            vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                                        }
                                        break;
                                    }
                                }
                                if (StringUtils.isBlank(vehicleLocalteInfo)) {
                                    vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
                                }
                            }
                            if (StringUtils.isBlank(vehicleLocalteInfo)) {
                                vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
                            }
                            if (StringUtils.isNotBlank(vehicleLocalteInfo)) {
                                HashMap calculateParam = new HashMap();
                                calculateParam.put("origin", vehicleLocalteInfo);
                                calculateParam.put("destination", destinationLocateInfo);
                                Long durationTime = GaoDeInfoUtils.calculateDistanceTime(calculateParam);
                                long sconds = duration.toMillis() / 1000;
                                if ((float) sconds / 3600 < ((float) durationTime / 3600)) {
                                    continue;
                                }
                                driverUserSortVo.setMobileLocate(durationTime);
                            } else {
                                //如果通过gps的获取的距离为空  那么  车不可用，直接将距离设置为无限大
                                driverUserSortVo.setMobileLocate(100000000000L);
                            }
                            HsmwUserDriver driver = hsmwUserDrivers.get(0);
                            //user 信息
                            String userId = driver.getUserId();
                            HsmwDriverUser hsmwUser = hsmwDriverUserMapper.selectById(userId);
                            driverUserSortVo.setDriverList(hsmwUserDrivers);
                            driverUserSortVo.setDriverId(driver.getId());
                            driverUserSortVo.setHsmwOrder(order);
                            driverUserSortVo.setHsmwVehicle(hsmwVehicle);
                            driverUserSortVo.setHsmwUser(hsmwUser);
                            driverUserSortVo.setScore(driver.getScore());
                            driverUserSortVo.setVehicleUnit(0);
                            corperateDriverUserSortVos.add(driverUserSortVo);
                        }
                    }
                    if(CollectionUtil.isNotEmpty(corperateDriverUserSortVos)){
                        corperateDriverUserSortVos = sortDriverUserSort(corperateDriverUserSortVos);
                        checkedDriverSortVO=corperateDriverUserSortVos.get(0);
                        checkedDriverSortVO.setVehicleOwnType(VehicleTypeEnum.CORPERATE.getValue());

                    }else{

                        //筛选 查询出来的平台车辆
                        if(StringUtils.isListNotNull(platformVehicles)) {
                            String imeiStrs = "";
                            String vehicleIds = "";
                            for (HsmwVehicle vehicle : platformVehicles) {
                                if (StringUtils.isNotBlank(vehicle.getImeiNum())) {
                                    imeiStrs += ("," + vehicle.getImeiNum());
                                    vehicleIds += ("," + vehicle.getIdentifyingCode());
                                }
                            }
                            //查询车辆是否能到
                            List<GpsInfoEntity> gpsInfoEntities = new ArrayList<>();
                            if (StringUtils.isNotBlank(imeiStrs)) {
                                gpsInfoEntities = GaoDeInfoUtils.getVehicleGpsLocate(imeiStrs,vehicleIds);
                            }
                            List<GpsInfoEntity> finalGpsInfoEntities = gpsInfoEntities;

                            for (HsmwVehicle hsmwVehicle :platformVehicles) {
                                List<HsmwRequestVehicle> hsmwRequestVehicles = hsmwRequestVehicleService.
                                        list(new LambdaQueryWrapper<HsmwRequestVehicle>()
                                                .eq(HsmwRequestVehicle::getVehilceId, hsmwVehicle.getId()).
                                                        eq(HsmwRequestVehicle::getForemanUserId, order.getItemId()));
                                if (CollectionUtil.isNotEmpty(hsmwRequestVehicles)) {
                                    continue;
                                }
                                // 查询接单中的司机 信息 如果没有接单中的司机那么 就不会进行派单
                                List<HsmwUserDriver> hsmwUserDrivers = hsmwUserDriverService.selectAvaliableList(hsmwVehicle.getId());
                                if(CollectionUtil.isEmpty(hsmwUserDrivers)){
                                    continue;
                                }
                                String vehicleId = hsmwVehicle.getId();
                                DriverUserSortVo driverUserSortVo = new DriverUserSortVo();
                                driverUserSortVo.setVehicleId(vehicleId);
                                //查询距离时间
                                String vehicleLocalteInfo = null;
                                String destinationLocateInfo = order.getLng() + "," + order.getLat();
                                if (finalGpsInfoEntities.size() > 0) {
                                    for (GpsInfoEntity entity : finalGpsInfoEntities) {
                                        if (entity.getDeviceId().equals(hsmwVehicle.getImeiNum()) || StringUtils.equals(entity.getDeviceId(),hsmwVehicle.getIdentifyingCode())) {
                                            if (StringUtils.isNotBlank(entity.getGpsLat())) {
                                                vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                                            }
                                            break;
                                        }
                                    }
                                    if (StringUtils.isBlank(vehicleLocalteInfo)) {
                                        vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
                                    }
                                }
                                if (StringUtils.isBlank(vehicleLocalteInfo)) {
                                    vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
                                }
                                if (StringUtils.isNotBlank(vehicleLocalteInfo)) {
                                    HashMap calculateParam = new HashMap();
                                    calculateParam.put("origin", vehicleLocalteInfo);
                                    calculateParam.put("destination", destinationLocateInfo);
                                    Long durationTime = GaoDeInfoUtils.calculateDistanceTime(calculateParam);
                                    long sconds = duration.toMillis() / 1000;
                                    if ((float) sconds / 3600 < ((float) durationTime / 3600)) {
                                        continue;
                                    }
                                    driverUserSortVo.setMobileLocate(durationTime);
                                } else {
                                    //如果通过gps的获取的距离为空  那么  车不可用，直接将距离设置为无限大
                                    driverUserSortVo.setMobileLocate(100000000000L);
                                }
                                HsmwUserDriver driver = hsmwUserDrivers.get(0);
                                //user 信息
                                String userId = driver.getUserId();
                                HsmwDriverUser hsmwUser = hsmwDriverUserMapper.selectById(userId);
                                driverUserSortVo.setDriverList(hsmwUserDrivers);
                                driverUserSortVo.setDriverId(driver.getId());
                                driverUserSortVo.setHsmwOrder(order);
                                driverUserSortVo.setHsmwVehicle(hsmwVehicle);
                                driverUserSortVo.setHsmwUser(hsmwUser);
                                driverUserSortVo.setScore(driver.getScore());
                                driverUserSortVo.setVehicleUnit(0);
                                platformDriverUserSortVos.add(driverUserSortVo);
                            }
                        }
                        if(CollectionUtil.isNotEmpty(platformDriverUserSortVos)){
                            platformDriverUserSortVos =sortDriverUserSort(platformDriverUserSortVos);
                            checkedDriverSortVO= platformDriverUserSortVos.get(0);
                            checkedDriverSortVO.setVehicleOwnType(VehicleTypeEnum.PLATEFORM.getValue());
                        }
                    }
                }
                //经过筛选，如果没有合适的司机就不进行派单
                if(StringUtils.isNotNull(checkedDriverSortVO)){
                    //如果该需求有合适的车 那么就把该需求的状态改为 已发布
                    hsmwOrderVehicleRequest.setRequestStatus(RequestStatusEnum.RECEIVED.getValue());
                    //如果hsmwOrderVehicleRequest 更新成功 那么直接进行子订单和司机相关的操作
                    if(hsmwOrderVehicleRelationService.checkIfVehicleWorking(checkedDriverSortVO.getVehicleId())){
                        //创建子订单信息
                        HsmwOrderVehicleRelation hsmwOrderVehicleRelation  = new HsmwOrderVehicleRelation();
                        String  relationId = CommonUtils.generateId(hsmwOrderVehicleRelation);
                        hsmwOrderVehicleRelation.setVehicleId(checkedDriverSortVO.getVehicleId());
                        hsmwOrderVehicleRelation.setOrderStatus(ChildOrderStatusEnum.RECEIVED.getValue());
                        hsmwOrderVehicleRelation.setOrderId(order.getId());
                        HsmwVehicle hsmwVehicle = checkedDriverSortVO.getHsmwVehicle();
                        hsmwOrderVehicleRelation.setImeiNum(hsmwVehicle.getImeiNum());
                        hsmwOrderVehicleRelation.setVehicleNum(hsmwVehicle.getVehiclePlate());
                        hsmwOrderVehicleRelation.setVehicleType(hsmwVehicle.getVehicleType());
                        hsmwOrderVehicleRelation.setVehicleModel(hsmwVehicle.getVehicleModel());
                        hsmwOrderVehicleRelation.setOrderVehicleRequestId(hsmwOrderVehicleRequest.getId());
                        hsmwOrderVehicleRelation.setExpectVolume(hsmwOrderVehicleRequest.getExpectVolume());
                        hsmwOrderVehicleRelation.setAcceptOrderTime(LocalDateTime.now());
                        hsmwOrderVehicleRelation.setId(relationId);
                        if(VehicleTypeEnum.PLATEFORM.getValue().equals(checkedDriverSortVO.getVehicleOwnType()) ){
                            hsmwOrderVehicleRelation.setOutsideLeasingFlag(CommonConstants.YES);
                        }
                        //插入数据前 判断数据是否已经改变。
                        if(hsmwOrderVehicleRequestService.compareAndUpdate(hsmwOrderVehicleRequest)) {
                            hsmwOrderVehicleRelationService.save(hsmwOrderVehicleRelation);
                            HsmwPumpOperateRecord record1 = new HsmwPumpOperateRecord();
                            record1.setOrderId(order.getId());
                            record1.setName(hsmwVehicle.getVehiclePlate());
                            record1.setUserType("");
                            record1.setCreateTime(LocalDateTime.now());
                            record1.setUsername(user.getUsername());
                            record1.setOrderStatus(PumpOrderStatusEnum.RECEIVED.getValue());
                            record1.setOperContent("接单 接单车辆为"+hsmwVehicle.getVehiclePlate());
                            hsmwPumpOperateRecordService.save(record1);
                            //针对筛选后的可以派单司机进行派单
                            //改车绑定的可用司机列表
                            List<HsmwUserDriver> hsmwUserDriverList =checkedDriverSortVO.getDriverList();
                            ///接单中的司机进行推送
                            if(CollectionUtil.isNotEmpty(hsmwUserDriverList)){
                                try {
                                    HsmwDriverUser user1 = hsmwDriverUserMapper.selectById(hsmwUserDriverList.get(0).getUserId());
                                    SingleCallByVoiceResponse singleCallByVoiceResponse = Sample.SingleCallByVoice(Sample.createDyvmsapiClient(), user1.getUsername(), voiceCode);
                                    HsmwMonitorDriverMessage hsmwMonitorDriverMessage = new HsmwMonitorDriverMessage();
                                    hsmwMonitorDriverMessage.setOrderId(order.getId());
                                    hsmwMonitorDriverMessage.setRelationId(relationId);
                                    hsmwMonitorDriverMessage.setVehicleId(hsmwVehicle.getId());
                                    hsmwMonitorDriverMessage.setDirverPhone(user1.getUsername());
                                    hsmwMonitorDriverMessage.setCallId(singleCallByVoiceResponse.body.callId);
                                    hsmwMonitorDriverMessageMapper.insert(hsmwMonitorDriverMessage);
                                    //Sample.QueryCallDetailByCallId(Sample.createDyvmsapiClient(), singleCallByVoiceResponse.body.callId, queryTime);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                for (HsmwUserDriver hsmwUserDriver : hsmwUserDriverList) {
                                    String userId1 = hsmwUserDriver.getUserId();
                                    HsmwDriverUser hsmwUsers = hsmwDriverUserMapper.selectById(userId1);
                                    if(hsmwUsers != null){
                                        TencentPushUtils.pushMsg("系统已为您指派订单，请尽快前往APP查看，确认出发时间，以免延误工作！", hsmwUsers.getUsername(),"order_status_2");
                                        String msg = "系统已为您指派订单，请尽快前往APP查看，确认出发时间，以免延误工作！";
                                        SendSmsUtil.sendDriverSmsCode(appId, appKey, msg,orderTimeoutNoticeBiz, smsSign, hsmwUsers.getUsername());
                                        SendSmsUtil.sendBizOrderForceSms(appId, appKey, hsmwUsers.getName(),hsmwUsers.getUsername(),textOrderTimeOut, smsSign, "13520391225");
                                        HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                                        hsmwDriverNews.setUserId(userId1);
                                        hsmwDriverNews.setMessage(msg);
                                        hsmwDriverNews.setAlreadyRead("0");
                                        hsmwDriverNewsService.save(hsmwDriverNews);
                                    }
                                }
                            }
                            //司机指派成功 则 将 司机状态改为 工作中
                            if (CollectionUtil.isNotEmpty(hsmwUserDriverList)){
                                hsmwUserDriverList.stream().forEach(hsmwUserDriver -> {
                                    hsmwUserDriver.setWorkStatus(CommonConstants.DRIVER_WORK);
                                });
                            }
                            hsmwUserDriverService.updateBatchById(hsmwUserDriverList);
                            //司机抢单成功 则 将 司机状态改为  工作中
                            hsmwVehicle.setWorkStatus(CommonConstants.DRIVER_WORK);
                            hsmwVehicleService.updateById(hsmwVehicle);
                        }
                    }
                }
            }
           HsmwOrderVehicleRequest request  = hsmwOrderVehicleRequestMapper.selectById(hsmwOrderVehicleRequest.getId());
            if(StringUtils.isBlank(request.getRequestStatus())){
                request.setRequestStatus(RequestStatusEnum.UNRECEIVED.getValue());
                hsmwOrderVehicleRequestService.updateById(request);
                if(CommonConstants.NO.equals(hsmwOrderVehicleRequest.getAppointOrder())){
                    undispatchRequest.add(request);
                }
            }
        });
        hsmwOrderMapper.updateById(order);
        returnVO.setRequestList(undispatchRequest);
        return returnVO;
    }


    public ReturnVO dispatchOrder(HsmwOrderVO order) {
        ReturnVO returnVO = new ReturnVO();
        LoginUser user = currentHsmwUserUtils.getCurrentUserInfo();
        List<HsmwOrderVehicleRequest> undispatchRequest = new ArrayList<>();
        //强制 派单 ==== 首选查询出来 该订单所有的需求信息
        List<HsmwOrderVehicleRequest> requestList =new ArrayList<>();
        HsmwOrderVehicleRequest hsmwOrderVehicleRequest = hsmwOrderVehicleRequestService.getById(order.getRequestId());
        //分别对每一个需求进行派单
            //如果是 指定司机的订单
            if(CommonConstants.YES.equals(hsmwOrderVehicleRequest.getAppointOrder()) && StringUtils.isNotBlank(hsmwOrderVehicleRequest.getAppointVehicleId())){
                HsmwVehicle vehicle = hsmwVehicleMapper.selectById(hsmwOrderVehicleRequest.getAppointVehicleId());
                if(CommonConstants.VEHICLE_FREE.equals(vehicle.getWorkStatus())){
                    //如果hsmwOrderVehicleRequest 更新成功 那么直接进行子订单和司机相关的操作
                    if (hsmwOrderVehicleRelationService.checkIfVehicleWorking(hsmwOrderVehicleRequest.getAppointVehicleId())) {
                        //如果是指定车辆的下单 那么 车上的司机 空闲中和接单中的司机 必须大于0 最小是1
                        List<HsmwUserDriver> hsmwUserDriverList = hsmwUserDriverService.selectAvaliableList(vehicle.getId());
                        if(CollectionUtil.isNotEmpty(hsmwUserDriverList)){
                            //创建子订单信息
                            HsmwOrderVehicleRelation hsmwOrderVehicleRelation = new HsmwOrderVehicleRelation();
                            String relationId = CommonUtils.generateId(hsmwOrderVehicleRelation);
                            hsmwOrderVehicleRelation.setVehicleId(hsmwOrderVehicleRequest.getAppointVehicleId());
                            //hsmwOrderVehicleRelation.setDriverName(checkedDriverSortVO.);
                            hsmwOrderVehicleRelation.setOrderStatus(ChildOrderStatusEnum.RECEIVED.getValue());
                            hsmwOrderVehicleRelation.setOrderId(order.getId());
                            HsmwVehicle hsmwVehicle =vehicle;
                            hsmwOrderVehicleRelation.setImeiNum(hsmwVehicle.getImeiNum());
                            hsmwOrderVehicleRelation.setVehicleNum(hsmwVehicle.getVehiclePlate());
                            hsmwOrderVehicleRelation.setVehicleType(hsmwVehicle.getVehicleType());
                            hsmwOrderVehicleRelation.setVehicleModel(hsmwVehicle.getVehicleModel());
                            hsmwOrderVehicleRelation.setOrderVehicleRequestId(hsmwOrderVehicleRequest.getId());
                            //hsmwOrderVehicleRelation.setReachTime(hsmwOrderVehicleRequest.getCreateTime());
                            hsmwOrderVehicleRelation.setExpectVolume(hsmwOrderVehicleRequest.getExpectVolume());
                            hsmwOrderVehicleRelation.setAcceptOrderTime(LocalDateTime.now());
                            hsmwOrderVehicleRelation.setId(relationId);
                            if(StringUtils.isNotBlank(hsmwOrderVehicleRequest.getOutsideLeasingFlag()) && CommonConstants.YES.equals(hsmwOrderVehicleRequest.getOutsideLeasingFlag())){
                                hsmwOrderVehicleRelation.setOutsideLeasingFlag(CommonConstants.YES);
                            }else {
                                hsmwOrderVehicleRelation.setOutsideLeasingFlag(CommonConstants.NO);
                            }
                            hsmwOrderVehicleRequest.setRequestStatus(RequestStatusEnum.RECEIVED.getValue());

                            //插入数据前 判断数据是否已经改变。
                            if (hsmwOrderVehicleRequestService.compareAndUpdate(hsmwOrderVehicleRequest)) {
                                hsmwOrderVehicleRelationService.save(hsmwOrderVehicleRelation);
                                HsmwPumpOperateRecord record1 = new HsmwPumpOperateRecord();
                                record1.setOrderId(order.getId());
                                record1.setName(hsmwVehicle.getVehiclePlate());
                                record1.setUserType("");
                                record1.setCreateTime(LocalDateTime.now());
                                record1.setUsername(user.getUsername());
                                record1.setOrderStatus(PumpOrderStatusEnum.RECEIVED.getValue());
                                record1.setOperContent("接单 接单车辆为" + hsmwVehicle.getVehiclePlate());
                                hsmwPumpOperateRecordService.save(record1);
                                //针对筛选后的可以派单司机进行派单
                                ///接单中的司机进行推送
                                if (CollectionUtil.isNotEmpty(hsmwUserDriverList)) {
                                    for (HsmwUserDriver hsmwUserDriver : hsmwUserDriverList) {
                                        String userId1 = hsmwUserDriver.getUserId();
                                        HsmwDriverUser hsmwUsers = hsmwDriverUserMapper.selectById(userId1);
                                        if (hsmwUsers != null) {
                                            TencentPushUtils.pushMsg("系统已为您指派订单，请尽快前往APP查看，确认出发时间，以免延误工作！", hsmwUsers.getUsername(), "order_status_2");
                                            String msg = "系统已为您指派订单，请尽快前往APP查看，确认出发时间，以免延误工作！";
                                            SendSmsUtil.sendDriverSmsCode(appId, appKey, msg, orderTimeoutNoticeBiz, smsSign, hsmwUsers.getUsername());
                                            SendSmsUtil.sendBizOrderForceSms(appId, appKey, hsmwUsers.getName(), hsmwUsers.getUsername(), textOrderTimeOut, smsSign, "13520391225");
                                            try {
                                                SingleCallByVoiceResponse singleCallByVoiceResponse = Sample.SingleCallByVoice(Sample.createDyvmsapiClient(), hsmwUsers.getUsername(), voiceCode);
                                                Sample.QueryCallDetailByCallId(Sample.createDyvmsapiClient(), singleCallByVoiceResponse.body.callId, queryTime);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                }
                                //司机指派成功 则 将 司机状态改为 工作中
                                if (CollectionUtil.isNotEmpty(hsmwUserDriverList)) {
                                    hsmwUserDriverList.stream().forEach(hsmwUserDriver -> {
                                        hsmwUserDriver.setWorkStatus(CommonConstants.DRIVER_WORK);
                                    });
                                }
                                hsmwUserDriverService.updateBatchById(hsmwUserDriverList);
                                //司机抢单成功 则 将 司机状态改为  工作中
                                hsmwVehicle.setWorkStatus(CommonConstants.DRIVER_WORK);
                                hsmwVehicleService.updateById(hsmwVehicle);
                            }
                        }
                    }
                }
            }else {
                //如果不是指定车辆的下单 则走正常的下单流程。
                java. time.Duration duration = java.time.Duration.between(LocalDateTime.now(),  hsmwOrderVehicleRequest.getReachTime());
                //自营车辆的派单vo
                List<DriverUserSortVo> selfrunUserSortVos = new ArrayList<>();
                //合作公司的派单VO
                List<DriverUserSortVo> corperateDriverUserSortVos = new ArrayList<>();
                //平台的其他的公司的派单VO
                List<DriverUserSortVo> platformDriverUserSortVos = new ArrayList<>();
                //选中的司机信息
                DriverUserSortVo checkedDriverSortVO = null;

                //自营车辆的司机列表
                List<HsmwVehicle> selfrunVehicles = new ArrayList<>();
                //合作公司的司机列表
                List<HsmwVehicle> corperateVehicles = new ArrayList<>();
                //平台的其他的公司的司机列表
                List<HsmwVehicle> platformVehicles = new ArrayList<>();

                HsmwHtnUser createUser = hsmwHtnUserMapper.selectById(order.getCreateUser());
                //如果是公司用户 那么直接查询本公司的车辆作为自营车辆
                String selfrunCompanyId ="";
                if(HtnUserTypeEnum.COMPANY.getValue().equals(createUser.getType())){
                    selfrunCompanyId= createUser.getOwnCompanyId();
                }
                //如果是搅拌站用户  则查询自营合作公司的Id
                if(HtnUserTypeEnum.CONCRETE.getValue().equals(createUser.getType())){
                    List<HsmwCorporationCompany> corporationCompanies = hsmwCorporationCompanyMapper.selectList(new LambdaQueryWrapper<HsmwCorporationCompany>()
                            .eq(HsmwCorporationCompany::getConcretePlantId,createUser.getOwnCompanyId())
                            .eq(HsmwCorporationCompany::getCorperateType, CorperateTypeEnum.SELFRUN.getValue()));
                    if(CollectionUtil.isNotEmpty(corporationCompanies)){
                        selfrunCompanyId= corporationCompanies.get(0).getCorperateCompanyId();
                    }
                }
                //如果下单人员是 工长或者项目的负责人
                //查询该项目绑定的泵送公司
                String itemCreateUserCompanyId=null;
                HsmwHtnUser itemCreator =null;
                if(HtnUserTypeEnum.FOREMAN.getValue().equals(createUser.getType())){
                    HsmwItem item = hsmwItemService.getHsmwItemById(order.getItemId());
                    itemCreator = hsmwHtnUserService.getHsmwUserById(item.getCreateUser());
                    itemCreateUserCompanyId=itemCreator.getOwnCompanyId();
                    if(StringUtils.isNotNull(itemCreator)){
                        if(HtnUserTypeEnum.COMPANY.getValue().equals(itemCreator.getType())){
                            selfrunCompanyId= itemCreator.getOwnCompanyId();
                        }
                        //如果是搅拌站用户  则查询自营合作公司的Id
                        if(HtnUserTypeEnum.CONCRETE.getValue().equals(itemCreator.getType())){
                            List<HsmwCorporationCompany> corporationCompanies = hsmwCorporationCompanyMapper.selectList(
                                    new LambdaQueryWrapper<HsmwCorporationCompany>()
                                            .eq(HsmwCorporationCompany::getConcretePlantId,itemCreator.getOwnCompanyId())
                                            .eq(HsmwCorporationCompany::getCorperateType, CorperateTypeEnum.SELFRUN.getValue()));
                            if(CollectionUtil.isNotEmpty(corporationCompanies)){
                                selfrunCompanyId= corporationCompanies.get(0).getCorperateCompanyId();
                            }
                        }
                    }
                }
                //当指定车辆的ID不为空的时候
                if(StringUtils.isNotBlank(selfrunCompanyId)){
                    hsmwOrderVehicleRequest.setLeasingCompanyId(selfrunCompanyId);
                    selfrunVehicles = hsmwOrderService.getIdleVehicleListByRequestId(hsmwOrderVehicleRequest,"1",createUser,null,itemCreator);
                }
                //租赁公司和搅拌站查询合作的公司的车辆
                corperateVehicles = hsmwOrderService.getIdleVehicleListByRequestId(  hsmwOrderVehicleRequest,"2",createUser,itemCreateUserCompanyId,itemCreator);

                // 查询平台的车辆 的车辆 默认不派平台车辆
                //只有开启了平台叫泵的才会查询平台车辆
                if(CommonConstants.YES.equals(order.getIfSelfChoose())){
                    platformVehicles = hsmwOrderService.getIdleVehicleListByRequestId(hsmwOrderVehicleRequest,"3",createUser,itemCreateUserCompanyId,itemCreator);
                }

                //筛选 查询出来的自营车辆
                if(StringUtils.isListNotNull(selfrunVehicles)) {
                    String imeiStrs = "";
                    String vehicleIds = "";
                    for (HsmwVehicle vehicle : selfrunVehicles) {
                        if (StringUtils.isNotBlank(vehicle.getImeiNum()) || StringUtils.isNotBlank(vehicle.getIdentifyingCode())) {
                            imeiStrs += ("," + vehicle.getImeiNum());
                            vehicleIds += ("," + vehicle.getIdentifyingCode());
                        }
                    }
                    //查询车辆是否能到
                    List<GpsInfoEntity> gpsInfoEntities = new ArrayList<>();
                    if (StringUtils.isNotBlank(imeiStrs)) {
                        gpsInfoEntities = GaoDeInfoUtils.getVehicleGpsLocate(imeiStrs,vehicleIds);
                    }
                    List<GpsInfoEntity> finalGpsInfoEntities = gpsInfoEntities;

                    for (HsmwVehicle hsmwVehicle :selfrunVehicles) {
                        List<HsmwRequestVehicle> hsmwRequestVehicles = hsmwRequestVehicleService.
                                list(new LambdaQueryWrapper<HsmwRequestVehicle>()
                                        .eq(HsmwRequestVehicle::getVehilceId, hsmwVehicle.getId()).
                                                eq(HsmwRequestVehicle::getForemanUserId, order.getItemId()));
                        if (CollectionUtil.isNotEmpty(hsmwRequestVehicles)) {
                            continue;
                        }

                        // 查询接单中的司机 信息 如果没有接单中的司机那么 就不会进行派单
                        List<HsmwUserDriver> hsmwUserDrivers = hsmwUserDriverService.selectAvaliableList(hsmwVehicle.getId());
                        if(CollectionUtil.isEmpty(hsmwUserDrivers)){
                            continue;
                        }
                        String vehicleId = hsmwVehicle.getId();
                        DriverUserSortVo driverUserSortVo = new DriverUserSortVo();
                        driverUserSortVo.setVehicleId(vehicleId);
                        //查询距离时间
                        String vehicleLocalteInfo = null;
                        String destinationLocateInfo = order.getLng() + "," + order.getLat();
                        if (finalGpsInfoEntities.size() > 0) {
                            for (GpsInfoEntity entity : finalGpsInfoEntities) {
                                if (entity.getDeviceId().equals(hsmwVehicle.getImeiNum()) || StringUtils.equals(entity.getDeviceId(),hsmwVehicle.getIdentifyingCode())) {
                                    if (StringUtils.isNotBlank(entity.getGpsLat())) {
                                        vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                                    }
                                    break;
                                }
                            }
                            if (StringUtils.isBlank(vehicleLocalteInfo)) {
                                vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
                            }
                        }
                        if (StringUtils.isBlank(vehicleLocalteInfo)) {
                            vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
                        }
                        if (StringUtils.isNotBlank(vehicleLocalteInfo)) {
                            HashMap calculateParam = new HashMap();
                            calculateParam.put("origin", vehicleLocalteInfo);
                            calculateParam.put("destination", destinationLocateInfo);
                            Long durationTime = GaoDeInfoUtils.calculateDistanceTime(calculateParam);
                            long sconds = duration.toMillis() / 1000;
                            if ((float) sconds / 3600 < ((float) durationTime / 3600)) {
                                continue;
                            }
                            driverUserSortVo.setMobileLocate(durationTime);
                        } else {
                            //如果通过gps的获取的距离为空  那么  车不可用，直接将距离设置为无限大
                            driverUserSortVo.setMobileLocate(100000000000L);
                        }
                        HsmwUserDriver driver = hsmwUserDrivers.get(0);
                        //user 信息
                        String userId = driver.getUserId();
                        HsmwDriverUser hsmwUser = hsmwDriverUserMapper.selectById(userId);
                        driverUserSortVo.setDriverList(hsmwUserDrivers);
                        driverUserSortVo.setDriverId(driver.getId());
                        driverUserSortVo.setHsmwOrder(order);
                        driverUserSortVo.setHsmwVehicle(hsmwVehicle);
                        driverUserSortVo.setHsmwUser(hsmwUser);
                        driverUserSortVo.setScore(driver.getScore());
                        driverUserSortVo.setVehicleUnit(0);
                        selfrunUserSortVos.add(driverUserSortVo);
                    }
                }
                if(CollectionUtil.isNotEmpty(selfrunUserSortVos)){
                    selfrunUserSortVos = sortDriverUserSort(selfrunUserSortVos);
                    checkedDriverSortVO = selfrunUserSortVos.get(0);
                    checkedDriverSortVO.setVehicleOwnType(VehicleTypeEnum.SELFRUN.getValue());
                    returnVO.setVehicleEnough(true);
                }else {
                    returnVO.setVehicleEnough(false);
                    //筛选 查询出来的平台车辆
                    if(StringUtils.isListNotNull(corperateVehicles)) {
                        String imeiStrs = "";
                        String vehicleIds = "";
                        for (HsmwVehicle vehicle : corperateVehicles) {
                            if (StringUtils.isNotBlank(vehicle.getImeiNum())) {
                                imeiStrs += ("," + vehicle.getImeiNum());
                                vehicleIds += ("," + vehicle.getIdentifyingCode());
                            }
                        }
                        //查询车辆是否能到
                        List<GpsInfoEntity> gpsInfoEntities = new ArrayList<>();
                        if (StringUtils.isNotBlank(imeiStrs)) {
                            gpsInfoEntities = GaoDeInfoUtils.getVehicleGpsLocate(imeiStrs,vehicleIds);
                        }
                        List<GpsInfoEntity> finalGpsInfoEntities = gpsInfoEntities;

                        for (HsmwVehicle hsmwVehicle :corperateVehicles) {
                            List<HsmwRequestVehicle> hsmwRequestVehicles = hsmwRequestVehicleService.
                                    list(new LambdaQueryWrapper<HsmwRequestVehicle>()
                                            .eq(HsmwRequestVehicle::getVehilceId, hsmwVehicle.getId()).
                                                    eq(HsmwRequestVehicle::getForemanUserId, order.getItemId()));
                            if (CollectionUtil.isNotEmpty(hsmwRequestVehicles)) {
                                continue;
                            }
                            // 查询接单中的司机 信息 如果没有接单中的司机那么 就不会进行派单
                            List<HsmwUserDriver> hsmwUserDrivers = hsmwUserDriverService.selectAvaliableList(hsmwVehicle.getId());
                            if(CollectionUtil.isEmpty(hsmwUserDrivers)){
                                continue;
                            }
                            String vehicleId = hsmwVehicle.getId();
                            DriverUserSortVo driverUserSortVo = new DriverUserSortVo();
                            driverUserSortVo.setVehicleId(vehicleId);
                            //查询距离时间
                            String vehicleLocalteInfo = null;
                            String destinationLocateInfo = order.getLng() + "," + order.getLat();
                            if (finalGpsInfoEntities.size() > 0) {
                                for (GpsInfoEntity entity : finalGpsInfoEntities) {
                                    if (entity.getDeviceId().equals(hsmwVehicle.getImeiNum()) || StringUtils.equals(entity.getDeviceId(),hsmwVehicle.getIdentifyingCode())) {
                                        if (StringUtils.isNotBlank(entity.getGpsLat())) {
                                            vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                                        }
                                        break;
                                    }
                                }
                                if (StringUtils.isBlank(vehicleLocalteInfo)) {
                                    vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
                                }
                            }
                            if (StringUtils.isBlank(vehicleLocalteInfo)) {
                                vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
                            }
                            if (StringUtils.isNotBlank(vehicleLocalteInfo)) {
                                HashMap calculateParam = new HashMap();
                                calculateParam.put("origin", vehicleLocalteInfo);
                                calculateParam.put("destination", destinationLocateInfo);
                                Long durationTime = GaoDeInfoUtils.calculateDistanceTime(calculateParam);
                                long sconds = duration.toMillis() / 1000;
                                if ((float) sconds / 3600 < ((float) durationTime / 3600)) {
                                    continue;
                                }
                                driverUserSortVo.setMobileLocate(durationTime);
                            } else {
                                //如果通过gps的获取的距离为空  那么  车不可用，直接将距离设置为无限大
                                driverUserSortVo.setMobileLocate(100000000000L);
                            }
                            HsmwUserDriver driver = hsmwUserDrivers.get(0);
                            //user 信息
                            String userId = driver.getUserId();
                            HsmwDriverUser hsmwUser = hsmwDriverUserMapper.selectById(userId);
                            driverUserSortVo.setDriverList(hsmwUserDrivers);
                            driverUserSortVo.setDriverId(driver.getId());
                            driverUserSortVo.setHsmwOrder(order);
                            driverUserSortVo.setHsmwVehicle(hsmwVehicle);
                            driverUserSortVo.setHsmwUser(hsmwUser);
                            driverUserSortVo.setScore(driver.getScore());
                            driverUserSortVo.setVehicleUnit(0);
                            corperateDriverUserSortVos.add(driverUserSortVo);
                        }
                    }
                    if(CollectionUtil.isNotEmpty(corperateDriverUserSortVos)){
                        corperateDriverUserSortVos = sortDriverUserSort(corperateDriverUserSortVos);
                        checkedDriverSortVO=corperateDriverUserSortVos.get(0);
                        checkedDriverSortVO.setVehicleOwnType(VehicleTypeEnum.CORPERATE.getValue());

                    }else{

                        //筛选 查询出来的平台车辆
                        if(StringUtils.isListNotNull(platformVehicles)) {
                            String imeiStrs = "";
                            String vehicleIds = "";
                            for (HsmwVehicle vehicle : platformVehicles) {
                                if (StringUtils.isNotBlank(vehicle.getImeiNum())) {
                                    imeiStrs += ("," + vehicle.getImeiNum());
                                    vehicleIds += ("," + vehicle.getIdentifyingCode());
                                }
                            }
                            //查询车辆是否能到
                            List<GpsInfoEntity> gpsInfoEntities = new ArrayList<>();
                            if (StringUtils.isNotBlank(imeiStrs)) {
                                gpsInfoEntities = GaoDeInfoUtils.getVehicleGpsLocate(imeiStrs,vehicleIds);
                            }
                            List<GpsInfoEntity> finalGpsInfoEntities = gpsInfoEntities;

                            for (HsmwVehicle hsmwVehicle :platformVehicles) {
                                List<HsmwRequestVehicle> hsmwRequestVehicles = hsmwRequestVehicleService.
                                        list(new LambdaQueryWrapper<HsmwRequestVehicle>()
                                                .eq(HsmwRequestVehicle::getVehilceId, hsmwVehicle.getId()).
                                                        eq(HsmwRequestVehicle::getForemanUserId, order.getItemId()));
                                if (CollectionUtil.isNotEmpty(hsmwRequestVehicles)) {
                                    continue;
                                }
                                // 查询接单中的司机 信息 如果没有接单中的司机那么 就不会进行派单
                                List<HsmwUserDriver> hsmwUserDrivers = hsmwUserDriverService.selectAvaliableList(hsmwVehicle.getId());
                                if(CollectionUtil.isEmpty(hsmwUserDrivers)){
                                    continue;
                                }
                                String vehicleId = hsmwVehicle.getId();
                                DriverUserSortVo driverUserSortVo = new DriverUserSortVo();
                                driverUserSortVo.setVehicleId(vehicleId);
                                //查询距离时间
                                String vehicleLocalteInfo = null;
                                String destinationLocateInfo = order.getLng() + "," + order.getLat();
                                if (finalGpsInfoEntities.size() > 0) {
                                    for (GpsInfoEntity entity : finalGpsInfoEntities) {
                                        if (entity.getDeviceId().equals(hsmwVehicle.getImeiNum()) || StringUtils.equals(entity.getDeviceId(),hsmwVehicle.getIdentifyingCode())) {
                                            if (StringUtils.isNotBlank(entity.getGpsLat())) {
                                                vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                                            }
                                            break;
                                        }
                                    }
                                    if (StringUtils.isBlank(vehicleLocalteInfo)) {
                                        vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
                                    }
                                }
                                if (StringUtils.isBlank(vehicleLocalteInfo)) {
                                    vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
                                }
                                if (StringUtils.isNotBlank(vehicleLocalteInfo)) {
                                    HashMap calculateParam = new HashMap();
                                    calculateParam.put("origin", vehicleLocalteInfo);
                                    calculateParam.put("destination", destinationLocateInfo);
                                    Long durationTime = GaoDeInfoUtils.calculateDistanceTime(calculateParam);
                                    long sconds = duration.toMillis() / 1000;
                                    if ((float) sconds / 3600 < ((float) durationTime / 3600)) {
                                        continue;
                                    }
                                    driverUserSortVo.setMobileLocate(durationTime);
                                } else {
                                    //如果通过gps的获取的距离为空  那么  车不可用，直接将距离设置为无限大
                                    driverUserSortVo.setMobileLocate(100000000000L);
                                }
                                HsmwUserDriver driver = hsmwUserDrivers.get(0);
                                //user 信息
                                String userId = driver.getUserId();
                                HsmwDriverUser hsmwUser = hsmwDriverUserMapper.selectById(userId);
                                driverUserSortVo.setDriverList(hsmwUserDrivers);
                                driverUserSortVo.setDriverId(driver.getId());
                                driverUserSortVo.setHsmwOrder(order);
                                driverUserSortVo.setHsmwVehicle(hsmwVehicle);
                                driverUserSortVo.setHsmwUser(hsmwUser);
                                driverUserSortVo.setScore(driver.getScore());
                                driverUserSortVo.setVehicleUnit(0);
                                platformDriverUserSortVos.add(driverUserSortVo);
                            }
                        }
                        if(CollectionUtil.isNotEmpty(platformDriverUserSortVos)){
                            platformDriverUserSortVos =sortDriverUserSort(platformDriverUserSortVos);
                            checkedDriverSortVO= platformDriverUserSortVos.get(0);
                            checkedDriverSortVO.setVehicleOwnType(VehicleTypeEnum.PLATEFORM.getValue());
                        }
                    }
                }
                //经过筛选，如果没有合适的司机就不进行派单
                if(StringUtils.isNotNull(checkedDriverSortVO)){
                    //如果该需求有合适的车 那么就把该需求的状态改为 已发布
                    hsmwOrderVehicleRequest.setRequestStatus(RequestStatusEnum.RECEIVED.getValue());
                    //如果hsmwOrderVehicleRequest 更新成功 那么直接进行子订单和司机相关的操作
                    if(hsmwOrderVehicleRelationService.checkIfVehicleWorking(checkedDriverSortVO.getVehicleId())){
                        //创建子订单信息
                        HsmwOrderVehicleRelation hsmwOrderVehicleRelation  = new HsmwOrderVehicleRelation();
                        String  relationId = CommonUtils.generateId(hsmwOrderVehicleRelation);
                        hsmwOrderVehicleRelation.setVehicleId(checkedDriverSortVO.getVehicleId());
                        hsmwOrderVehicleRelation.setOrderStatus(ChildOrderStatusEnum.RECEIVED.getValue());
                        hsmwOrderVehicleRelation.setOrderId(order.getId());
                        HsmwVehicle hsmwVehicle = checkedDriverSortVO.getHsmwVehicle();
                        hsmwOrderVehicleRelation.setImeiNum(hsmwVehicle.getImeiNum());
                        hsmwOrderVehicleRelation.setVehicleNum(hsmwVehicle.getVehiclePlate());
                        hsmwOrderVehicleRelation.setVehicleType(hsmwVehicle.getVehicleType());
                        hsmwOrderVehicleRelation.setVehicleModel(hsmwVehicle.getVehicleModel());
                        hsmwOrderVehicleRelation.setOrderVehicleRequestId(hsmwOrderVehicleRequest.getId());
                        hsmwOrderVehicleRelation.setExpectVolume(hsmwOrderVehicleRequest.getExpectVolume());
                        hsmwOrderVehicleRelation.setAcceptOrderTime(LocalDateTime.now());
                        hsmwOrderVehicleRelation.setId(relationId);
                        if(VehicleTypeEnum.PLATEFORM.getValue().equals(checkedDriverSortVO.getVehicleOwnType()) ){
                            hsmwOrderVehicleRelation.setOutsideLeasingFlag(CommonConstants.YES);
                        }
                        //插入数据前 判断数据是否已经改变。
                        if(hsmwOrderVehicleRequestService.compareAndUpdate(hsmwOrderVehicleRequest)) {
                            hsmwOrderVehicleRelationService.save(hsmwOrderVehicleRelation);
                            HsmwPumpOperateRecord record1 = new HsmwPumpOperateRecord();
                            record1.setOrderId(order.getId());
                            record1.setName(hsmwVehicle.getVehiclePlate());
                            record1.setUserType("");
                            record1.setCreateTime(LocalDateTime.now());
                            record1.setUsername(user.getUsername());
                            record1.setOrderStatus(PumpOrderStatusEnum.RECEIVED.getValue());
                            record1.setOperContent("接单 接单车辆为"+hsmwVehicle.getVehiclePlate());
                            hsmwPumpOperateRecordService.save(record1);
                            //针对筛选后的可以派单司机进行派单
                            //改车绑定的可用司机列表
                            List<HsmwUserDriver> hsmwUserDriverList =checkedDriverSortVO.getDriverList();
                            ///接单中的司机进行推送
                            if(CollectionUtil.isNotEmpty(hsmwUserDriverList)){
                                try {
                                    HsmwDriverUser user1 = hsmwDriverUserMapper.selectById(hsmwUserDriverList.get(0).getUserId());
                                    SingleCallByVoiceResponse singleCallByVoiceResponse = Sample.SingleCallByVoice(Sample.createDyvmsapiClient(), user1.getUsername(), voiceCode);
                                    HsmwMonitorDriverMessage hsmwMonitorDriverMessage = new HsmwMonitorDriverMessage();
                                    hsmwMonitorDriverMessage.setOrderId(order.getId());
                                    hsmwMonitorDriverMessage.setRelationId(relationId);
                                    hsmwMonitorDriverMessage.setVehicleId(hsmwVehicle.getId());
                                    hsmwMonitorDriverMessage.setDirverPhone(user1.getUsername());
                                    hsmwMonitorDriverMessage.setCallId(singleCallByVoiceResponse.body.callId);
                                    hsmwMonitorDriverMessageMapper.insert(hsmwMonitorDriverMessage);
                                    //Sample.QueryCallDetailByCallId(Sample.createDyvmsapiClient(), singleCallByVoiceResponse.body.callId, queryTime);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                for (HsmwUserDriver hsmwUserDriver : hsmwUserDriverList) {
                                    String userId1 = hsmwUserDriver.getUserId();
                                    HsmwDriverUser hsmwUsers = hsmwDriverUserMapper.selectById(userId1);
                                    if(hsmwUsers != null){
                                        TencentPushUtils.pushMsg("系统已为您指派订单，请尽快前往APP查看，确认出发时间，以免延误工作！", hsmwUsers.getUsername(),"order_status_2");
                                        String msg = "系统已为您指派订单，请尽快前往APP查看，确认出发时间，以免延误工作！";
                                        SendSmsUtil.sendDriverSmsCode(appId, appKey, msg,orderTimeoutNoticeBiz, smsSign, hsmwUsers.getUsername());
                                        SendSmsUtil.sendBizOrderForceSms(appId, appKey, hsmwUsers.getName(),hsmwUsers.getUsername(),textOrderTimeOut, smsSign, "13520391225");
                                        HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                                        hsmwDriverNews.setUserId(userId1);
                                        hsmwDriverNews.setMessage(msg);
                                        hsmwDriverNews.setAlreadyRead("0");
                                        hsmwDriverNewsService.save(hsmwDriverNews);
                                    }
                                }
                            }
                            //司机指派成功 则 将 司机状态改为 工作中
                            if (CollectionUtil.isNotEmpty(hsmwUserDriverList)){
                                hsmwUserDriverList.stream().forEach(hsmwUserDriver -> {
                                    hsmwUserDriver.setWorkStatus(CommonConstants.DRIVER_WORK);
                                });
                            }
                            hsmwUserDriverService.updateBatchById(hsmwUserDriverList);
                            //司机抢单成功 则 将 司机状态改为  工作中
                            hsmwVehicle.setWorkStatus(CommonConstants.DRIVER_WORK);
                            hsmwVehicleService.updateById(hsmwVehicle);
                        }
                    }
                }
            }
            HsmwOrderVehicleRequest request  = hsmwOrderVehicleRequestMapper.selectById(hsmwOrderVehicleRequest.getId());
            if(StringUtils.isBlank(request.getRequestStatus())){
                request.setRequestStatus(RequestStatusEnum.UNRECEIVED.getValue());
                hsmwOrderVehicleRequestService.updateById(request);
                if(CommonConstants.NO.equals(hsmwOrderVehicleRequest.getAppointOrder())){
                    undispatchRequest.add(request);
                }
            }
        hsmwOrderMapper.updateById(order);
        returnVO.setRequestList(undispatchRequest);
        return returnVO;
    }
    public static List<DriverUserSortVo> sortDriverUserSort(List<DriverUserSortVo> vos) {
        //如果选择的是
        Collections.sort(vos, new Comparator<DriverUserSortVo>() {
            @Override
            public int compare(DriverUserSortVo v1, DriverUserSortVo v2) {
                if (v2.getVehicleUnit() != (v1.getVehicleUnit())) {
                    return (v2.getVehicleUnit() - v1.getVehicleUnit());
                } else {
                    if(v2.getScore()!=v1.getScore()){
                        return Integer.parseInt(v2.getScore()) - Integer.parseInt(v1.getScore());
                    }else {
                        return (int)(v1.getMobileLocate() -v2.getMobileLocate());
                    }
                }
            }
        });
        return vos;
    }


    public OrderCountResultVO getOrderInfoCount(HashMap param) {
        OrderCountResultVO vo = hsmwOrderMapper.getOrderInfoCount(param);
        return vo;
    }


    public IPage<HsmwOrder> getHsmwOrderPage(IPage page, HsmwOrder hsmwOrder) {
        LambdaQueryWrapper<HsmwOrder> lambdaQuery = Wrappers.lambdaQuery(HsmwOrder.class);
        if (StrUtil.isNotBlank(hsmwOrder.getOrderStatus()) && !hsmwOrder.getOrderStatus().equals("all")) {
            lambdaQuery.eq(HsmwOrder::getOrderStatus, hsmwOrder.getOrderStatus());
        }
        if (StrUtil.isNotBlank(hsmwOrder.getId())) {
            lambdaQuery.like(HsmwOrder::getId, hsmwOrder.getId());
        }
        if (StrUtil.isNotBlank(hsmwOrder.getItemName())) {
            lambdaQuery.like(HsmwOrder::getItemName, hsmwOrder.getItemName());
        }
        if (StrUtil.isNotBlank(hsmwOrder.getConstructionUnitName())) {
            lambdaQuery.like(HsmwOrder::getConstructionUnitName, hsmwOrder.getConstructionUnitName());
        }
        lambdaQuery.orderByDesc(HsmwOrder::getCreateTime);
        IPage<HsmwOrder> orderIPage = hsmwOrderMapper.selectPage(page, lambdaQuery);
        return orderIPage;
    }


    public void saveOrUpdateHsmwOrder(HsmwOrderVO hsmwOrderVO) {
        //新增订单信息
        if (StrUtil.isBlank(hsmwOrderVO.getId())) {
            hsmwOrderVO.setId(GenerateIDUtils.generateId(hsmwOrderVO));
            int reqCount = 0;
            if (StringUtils.isListNotNull(hsmwOrderVO.getVehicleRequestList())) {
                reqCount = hsmwOrderVO.getVehicleRequestList().stream().mapToInt(HsmwOrderVehicleRequest::getVehicleNumber).sum();
            }
            LoginUser currentUser = currentHsmwUserUtils.getCurrentUserInfo();
            hsmwOrderVO.setCreateUserTel(currentUser.getUsername());
            hsmwOrderVO.setReqCount(String.valueOf(reqCount));
            hsmwOrderVO.setOrderSn(RandomUtil.randomUUID());
            hsmwOrderVO.setCreateName(currentUser.getName());
            hsmwOrderVO.setCreateUser(currentUser.getId());
            HsmwItem hsmwItem = hsmwItemService.getById(hsmwOrderVO.getItemId());
            hsmwOrderVO.setItemName(hsmwItem.getName());
            hsmwOrderVO.setItemPosition(hsmwItem.getPosition());
            hsmwOrderVO.setLng(hsmwItem.getLng());
            hsmwOrderVO.setLat(hsmwItem.getLat());
            HsmwConstructionUnit hsmwConstructionUnit = hsmwConstructionUnitService.getById(hsmwOrderVO.getConstructionUnitId());
            hsmwOrderVO.setConstructionUnitName(hsmwConstructionUnit.getName());
            hsmwOrderVO.setConstructionUnitLinkMan(hsmwConstructionUnit.getLinkMan());
            hsmwOrderVO.setConstructionUnitTel(hsmwConstructionUnit.getTel());
            //hsmwOrderVO.setOrderStatus(MainOrderStatusEnum.CREATESUCCESS.getValue());
            this.save(hsmwOrderVO);
            handleSaveOrderData(hsmwOrderVO);
        } else {
            HsmwOrder oldHsmwOrder = hsmwOrderMapper.selectById(hsmwOrderVO.getId());
            Map<String, Object> columnMap = Maps.newHashMap();
            columnMap.put("order_id", oldHsmwOrder.getId());
            hsmwOrderForceManRelationMapper.deleteByMap(columnMap);
            hsmwOrderVehicleRequestMapper.deleteByMap(columnMap);
            List<HsmwHtnUser> hsmwUserList = hsmwHtnUserService.list(Wrappers.lambdaQuery(HsmwHtnUser.class).eq(HsmwHtnUser::getItemId, oldHsmwOrder.getItemId()));
            hsmwUserList.stream().forEach(x -> x.setItemId(""));
            hsmwHtnUserService.updateBatchById(hsmwUserList);
            HsmwItem hsmwItem = hsmwItemService.getById(hsmwOrderVO.getItemId());
            hsmwOrderVO.setItemName(hsmwItem.getName());
            hsmwOrderVO.setItemPosition(hsmwItem.getPosition());
            HsmwConstructionUnit hsmwConstructionUnit = hsmwConstructionUnitService.getById(hsmwOrderVO.getConstructionUnitId());
            hsmwOrderVO.setConstructionUnitName(hsmwConstructionUnit.getName());
            hsmwOrderVO.setConstructionUnitLinkMan(hsmwConstructionUnit.getLinkMan());
            hsmwOrderVO.setConstructionUnitTel(hsmwConstructionUnit.getTel());
            int reqCount = 0;
            if (StringUtils.isListNotNull(hsmwOrderVO.getVehicleRequestList())) {
                reqCount = hsmwOrderVO.getVehicleRequestList().stream().mapToInt(HsmwOrderVehicleRequest::getVehicleNumber).sum();
            }
            hsmwOrderVO.setReqCount(String.valueOf(reqCount));
            this.updateById(hsmwOrderVO);
            handleSaveOrderData(hsmwOrderVO);
        }
        //订单创建完直接进行发布
        publishHsmwOrder(hsmwOrderVO);

    }

    private void handleSaveOrderData(HsmwOrderVO hsmwOrderVO) {
        //工长不需要进行选择了
        //所需车辆
        hsmwOrderVO.getVehicleRequestList()
                .stream()
                .forEach(hsmwOrderVehicleRequest -> {
                    hsmwOrderVehicleRequest.setOrderId(hsmwOrderVO.getId());
                    hsmwOrderVehicleRequest.setRequestStatus(OrderStatusEnum.UNRECEIVED.getValue());
                    hsmwOrderVehicleRequest.setRemainVehicleNumber(hsmwOrderVehicleRequest.getVehicleNumber());
                });
        hsmwOrderVehicleRequestService.saveBatch(hsmwOrderVO.getVehicleRequestList());
    }

    public HsmwOrderVO getHsmwOrderById(String id) {
        HsmwOrderVO hsmwOrderVO = new HsmwOrderVO();
        BeanUtil.copyProperties(hsmwOrderMapper.selectById(id), hsmwOrderVO);
        List<HsmwOrderForceManRelation> hsmwOrderForceManRelationList = hsmwOrderForceManRelationService.list(Wrappers.lambdaQuery(HsmwOrderForceManRelation.class).eq(HsmwOrderForceManRelation::getOrderId, id));
        //hsmwOrderVO.setForceManRelations(hsmwOrderForceManRelationList);
        List<HsmwOrderVehicleRequest> hsmwOrderVehicleRequestList = hsmwOrderVehicleRequestService.list(Wrappers.lambdaQuery(HsmwOrderVehicleRequest.class).eq(HsmwOrderVehicleRequest::getOrderId, id));
        hsmwOrderVO.setVehicleRequestList(hsmwOrderVehicleRequestList);
        List<HsmwOrderVehicleRelation> vehicleRelationList = hsmwOrderVehicleRelationService.list(new LambdaQueryWrapper<HsmwOrderVehicleRelation>().eq(HsmwOrderVehicleRelation::getOrderId, id));
        hsmwOrderVO.setVehicleRelationList(vehicleRelationList);
        return hsmwOrderVO;
    }

    public List<GetRequestVehicleListDTO> getRequestVehicleListByOrderId(String orderId) {
        List<GetRequestVehicleListDTO> chooseVehicleList = Lists.newArrayList();
        List<HsmwOrderVehicleRequest> hsmwOrderVehicleRequestList = hsmwOrderVehicleRequestService.list(Wrappers.lambdaQuery(HsmwOrderVehicleRequest.class).eq(HsmwOrderVehicleRequest::getOrderId, orderId));
        hsmwOrderVehicleRequestList.forEach(hsmwOrderVehicleRequest -> {
            LambdaQueryWrapper<HsmwVehicle> lambdaQueryWrapper = Wrappers.lambdaQuery(HsmwVehicle.class);
            GetRequestVehicleListDTO getRequestVehicleListDto = new GetRequestVehicleListDTO();
            getRequestVehicleListDto.setHsmwOrderVehicleRequest(hsmwOrderVehicleRequest);
            lambdaQueryWrapper.eq(HsmwVehicle::getVehicleModel, hsmwOrderVehicleRequest.getVehicleModel());
            lambdaQueryWrapper.eq(HsmwVehicle::getVehicleType, hsmwOrderVehicleRequest.getVehicleType());
            List<String> vehicleStatus = new ArrayList<>();
            vehicleStatus.add(CommonConstants.VEHICLE_FREE);
            vehicleStatus.add(CommonConstants.VEHICLE_WORK);
            lambdaQueryWrapper.in(HsmwVehicle::getWorkStatus, vehicleStatus);
            List<HsmwVehicle> hsmwVehicleList = hsmwVehicleService.list(lambdaQueryWrapper);
            Set<String> vehicleIdSet = hsmwVehicleList.stream().map(HsmwVehicle::getId).collect(Collectors.toSet());
            if (CollectionUtil.isNotEmpty(vehicleIdSet)) {
                Map<String, List<HsmwUserDriver>> vehicleDriverMap = hsmwUserDriverMapper.selectList(Wrappers.lambdaQuery(HsmwUserDriver.class)
                        .in(HsmwUserDriver::getVehicleId, vehicleIdSet).in(HsmwUserDriver::getWorkStatus, CommonConstants.DRIVER_ACCEPT_ORDER))
                        .stream()
                        .peek(System.out::println)
                        .collect(Collectors.groupingBy(HsmwUserDriver::getVehicleId));
                Iterator<HsmwVehicle> iterator = hsmwVehicleList.iterator();
                while (iterator.hasNext()) {
                    HsmwVehicle hsmwVehicle = iterator.next();
                    if (CollectionUtil.isEmpty(vehicleDriverMap.get(hsmwVehicle.getId()))) {
                        iterator.remove();
                    }
                }
                getRequestVehicleListDto.setHsmwVehicleList(hsmwVehicleList);
            }
            chooseVehicleList.add(getRequestVehicleListDto);
        });
        return chooseVehicleList;
    }

    //通过需求ID 获取符合该需求的车辆信息
    public GetRequestVehicleListDTO getRequestVehicleListByRequestId(HsmwOrderVehicleRequest hsmwOrderVehicleRequest) {
        LambdaQueryWrapper<HsmwVehicle> lambdaQueryWrapper = Wrappers.lambdaQuery(HsmwVehicle.class);
        GetRequestVehicleListDTO getRequestVehicleListDto = new GetRequestVehicleListDTO();
        List<HsmwVehicle> avaliableVehicles = new ArrayList<>(128);
        getRequestVehicleListDto.setHsmwOrderVehicleRequest(hsmwOrderVehicleRequest);
        lambdaQueryWrapper.eq(HsmwVehicle::getVehicleModel, hsmwOrderVehicleRequest.getVehicleModel());
        lambdaQueryWrapper.eq(HsmwVehicle::getVehicleType, hsmwOrderVehicleRequest.getVehicleType());
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        //如果选择的桥数 不为空 则 在选择车的时候过滤一下。
        if (StringUtils.isNotBlank(hsmwOrderVehicleRequest.getAxis())) {
            List<String> axisList = new ArrayList<>();
            String axis = hsmwOrderVehicleRequest.getAxis();
            String[] axiss =axis.split(",");
            if(axiss.length>0){
                for(String ax:axiss){
                    axisList.add(ax);
                }
            }
            lambdaQueryWrapper.in(HsmwVehicle::getAxis, axisList);
        }
        //如果选择的臂节数 不为空 则 在选择车的时候过滤一下。
        if (StringUtils.isNotBlank(hsmwOrderVehicleRequest.getArmSegment())) {
            List<String> segList = new ArrayList<>();

            String segs = hsmwOrderVehicleRequest.getArmSegment();

            String[] segss =segs.split(",");
            if(segss.length>0){
                for(String ax:segss){
                    segList.add(ax);
                }
            }
            lambdaQueryWrapper.in(HsmwVehicle::getArmSegment, segList);
        }
        List<String> vehicleStatus = new ArrayList<>();
        vehicleStatus.add(CommonConstants.VEHICLE_FREE);
        lambdaQueryWrapper.in(HsmwVehicle::getWorkStatus, vehicleStatus);
        //首先查询出来符合的车辆
        List<HsmwVehicle> hsmwVehicleList = hsmwVehicleService.list(lambdaQueryWrapper);
        HsmwOrder order = hsmwOrderService.getHsmwOrderById(hsmwOrderVehicleRequest.getOrderId());
        //判断车辆年限
        if(CollectionUtil.isNotEmpty(hsmwVehicleList) && StringUtils.isNotBlank(hsmwOrderVehicleRequest.getYears()) ){
            Iterator<HsmwVehicle> iterator = hsmwVehicleList.iterator();
            while (iterator.hasNext()) {
                HsmwVehicle hsmwVehicle = iterator.next();
                LocalDate beginDate = hsmwVehicle.getBeginTime();
                if(StringUtils.isNull(beginDate)){
                    beginDate=LocalDate.now().minusMonths(12);
                }
                long year = beginDate.until(LocalDateTime.now(), ChronoUnit.YEARS);
                long month = beginDate.until(LocalDateTime.now(), ChronoUnit.MONTHS);
                double years = month/12.0;
                String yearStr =order.getYears();
                boolean isFitable= false;
                if(StringUtils.isNotBlank(yearStr)){
                    String[] yearSub = yearStr.split(",");
                    if(yearSub.length>0){
                        for(String str :yearSub){
                            double[] between =  getYearBetween(str);
                            double begin = between[0];
                            double end = between[1];
                            if(years<=end && years>begin){
                                isFitable=true;
                                break;
                            }
                        }
                    }
                }
                if(!isFitable){
                    iterator.remove();
                }
            }
        }
        Set<String> appointVehicleIdSet = hsmwVehicleList.stream().map(HsmwVehicle::getId).collect(Collectors.toSet());
        if (CollectionUtil.isNotEmpty(appointVehicleIdSet)) {
            List<String> status = new ArrayList<>();
            status.add(CommonConstants.DRIVER_ACCEPT_ORDER);
            Map<String, List<HsmwUserDriver>> vehicleDriverMap = hsmwUserDriverMapper.selectList(Wrappers.lambdaQuery(HsmwUserDriver.class)
                    .in(HsmwUserDriver::getVehicleId, appointVehicleIdSet).in(HsmwUserDriver::getWorkStatus, status))
                    .stream()
                    .peek(System.out::println)
                    .collect(Collectors.groupingBy(HsmwUserDriver::getVehicleId));
            Iterator<HsmwVehicle> iterator1 = hsmwVehicleList.iterator();
            while (iterator1.hasNext()) {
                HsmwVehicle hsmwVehicle = iterator1.next();
                HashMap param = new HashMap();
                param.put("vehicleId", hsmwVehicle.getId());
                param.put("reachTime", dtf.format(hsmwOrderVehicleRequest.getReachTime()));
                if (CollectionUtil.isEmpty(vehicleDriverMap.get(hsmwVehicle.getId()))) {
                    iterator1.remove();
                } else if (hsmwReportService.checkIfHasleavingRecord(param)) {
                    iterator1.remove();
                }
            }
            avaliableVehicles.addAll(hsmwVehicleList);
        }
        getRequestVehicleListDto.setHsmwVehicleList(avaliableVehicles);
        return getRequestVehicleListDto;
    }

    //通过需求ID 获取符合该需求的车辆信息 自营 合作 平台 三种类型
    public List<HsmwVehicle> getVehicleListByRequestId(HsmwOrderVehicleRequest hsmwOrderVehicleRequest,String type,HsmwHtnUser createuser,String itemCreateUserCompanyId,HsmwHtnUser itemCreator) {
        LambdaQueryWrapper<HsmwVehicle> lambdaQueryWrapper = Wrappers.lambdaQuery(HsmwVehicle.class);
        List<HsmwVehicle> avaliableVehicles = new ArrayList<>(128);
        if(hsmwOrderVehicleRequest.isFlag()){
            lambdaQueryWrapper.ne(HsmwVehicle::getVehicleModel, hsmwOrderVehicleRequest.getVehicleModel());
        }else {
            lambdaQueryWrapper.eq(HsmwVehicle::getVehicleModel, hsmwOrderVehicleRequest.getVehicleModel());
            lambdaQueryWrapper.eq(HsmwVehicle::getVehicleType, hsmwOrderVehicleRequest.getVehicleType());
        }
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        //如果选择的桥数 不为空 则 在选择车的时候过滤一下。
        List<String> axisList = new ArrayList<>();
        if (StringUtils.isNotBlank(hsmwOrderVehicleRequest.getAxis())) {
            String axis = hsmwOrderVehicleRequest.getAxis();
            String[] axiss =axis.split(",");
            if(axiss.length>0){
                for(String ax:axiss){
                    axisList.add(ax);
                }
            }
            lambdaQueryWrapper.in(HsmwVehicle::getAxis, axisList);
        }
        //如果选择的臂节数 不为空 则 在选择车的时候过滤一下。
        List<String> segList = new ArrayList<>();
        if (StringUtils.isNotBlank(hsmwOrderVehicleRequest.getArmSegment())) {
            String segs = hsmwOrderVehicleRequest.getArmSegment();
            String[] segss =segs.split(",");
            if(segss.length>0){
                for(String ax:segss){
                    segList.add(ax);
                }
            }
            lambdaQueryWrapper.in(HsmwVehicle::getArmSegment, segList);
        }
        List<String> vehicleStatus = new ArrayList<>();
        vehicleStatus.add(CommonConstants.VEHICLE_FREE);
        lambdaQueryWrapper.in(HsmwVehicle::getWorkStatus, vehicleStatus);
        //首先查询出来符合的车辆
        List<HsmwVehicle> hsmwVehicleList=new ArrayList<>();
        //如果是自营的车辆列表那么
        if(CorperateTypeEnum.SELFRUN.getValue().equals(type)){
            lambdaQueryWrapper.eq(HsmwVehicle::getLeasingCompanyId,hsmwOrderVehicleRequest.getLeasingCompanyId());
            hsmwVehicleList = hsmwVehicleService.list(lambdaQueryWrapper);
        }
        if(CorperateTypeEnum.ALL.getValue().equals(type)){
            hsmwVehicleList = hsmwVehicleService.list(lambdaQueryWrapper);
        }
        if(CorperateTypeEnum.CORPERATE.getValue().equals(type)){
            LambdaQueryWrapper<HsmwCorporationCompany> lambdaQueryWrapper1= new LambdaQueryWrapper<HsmwCorporationCompany>();
            if(HtnUserTypeEnum.COMPANY.getValue().equals(createuser.getType())){
                lambdaQueryWrapper1.eq(HsmwCorporationCompany::getCompanyId,createuser.getOwnCompanyId());
            }
            if(HtnUserTypeEnum.CONCRETE.getValue().equals(createuser.getType())){
                lambdaQueryWrapper1.eq(HsmwCorporationCompany::getConcretePlantId,createuser.getOwnCompanyId());
            }
            if(HtnUserTypeEnum.FOREMAN.getValue().equals(createuser.getType())){
                if(HtnUserTypeEnum.COMPANY.getValue().equals(itemCreator.getType())){
                    lambdaQueryWrapper1.eq(HsmwCorporationCompany::getCompanyId,itemCreator.getOwnCompanyId());
                }
                if(HtnUserTypeEnum.CONCRETE.getValue().equals(itemCreator.getType())){
                    lambdaQueryWrapper1.eq(HsmwCorporationCompany::getConcretePlantId,itemCreator.getOwnCompanyId());
                }
            }
            lambdaQueryWrapper1.eq(HsmwCorporationCompany::getCorperateType,CorperateTypeEnum.CORPERATE.getValue());
            List<HsmwCorporationCompany> corporationCompanies = hsmwCorporationCompanyMapper.selectList(lambdaQueryWrapper1);
            if(CollectionUtil.isNotEmpty(corporationCompanies)){
                Set<String> companyIds  =new HashSet<>();
                companyIds  = corporationCompanies.stream().map(HsmwCorporationCompany::getCorperateCompanyId).collect(Collectors.toSet());
                lambdaQueryWrapper.in(HsmwVehicle::getLeasingCompanyId,companyIds);
            }
            //当合作公司的车辆不为空的时候 才会查询合作公司的车辆
            if(CollectionUtil.isNotEmpty(corporationCompanies)){
                hsmwVehicleList = hsmwVehicleService.list(lambdaQueryWrapper);
            }
        }
        if(!CorperateTypeEnum.CORPERATE.getValue().equals(type) && !CorperateTypeEnum.SELFRUN.getValue().equals(type) && !CorperateTypeEnum.ALL.getValue().equals(type)){
            HashMap param =  new HashMap();
            if(HtnUserTypeEnum.FOREMAN.getValue().equals(createuser.getType())){
                param.put("companyId",itemCreator.getOwnCompanyId());
            }else {
                param.put("companyId",createuser.getOwnCompanyId());
            }
            if(StringUtils.isNotBlank(hsmwOrderVehicleRequest.getVehicleType())){
                param.put("vehicleType",hsmwOrderVehicleRequest.getVehicleType());
            }
            if(StringUtils.isNotBlank(hsmwOrderVehicleRequest.getVehicleModel())){
                param.put("vehicleModel",hsmwOrderVehicleRequest.getVehicleModel());
            }
            if(CollectionUtil.isNotEmpty(segList)){
                param.put("segList",segList);
            }
            if(CollectionUtil.isNotEmpty(axisList)){
                param.put("axisList",axisList);
            }
            hsmwVehicleList=hsmwVehicleService.selectPlateformVehicles(param);
        }
        //首先查询出来符合的车辆

        HsmwOrder order = hsmwOrderService.getHsmwOrderById(hsmwOrderVehicleRequest.getOrderId());
        //判断车辆年限
        if(CollectionUtil.isNotEmpty(hsmwVehicleList) && StringUtils.isNotBlank(hsmwOrderVehicleRequest.getYears()) ){
            Iterator<HsmwVehicle> iterator = hsmwVehicleList.iterator();
            while (iterator.hasNext()) {
                HsmwVehicle hsmwVehicle = iterator.next();
                LocalDate beginDate = hsmwVehicle.getBeginTime();
                if(StringUtils.isNull(beginDate)){
                    beginDate=LocalDate.now().minusMonths(12);
                }
                long year = beginDate.until(LocalDateTime.now(), ChronoUnit.YEARS);
                long month = beginDate.until(LocalDateTime.now(), ChronoUnit.MONTHS);
                double years = month/12.0;
                String yearStr =order.getYears();
                boolean isFitable= false;
                if(StringUtils.isNotBlank(yearStr)){
                    String[] yearSub = yearStr.split(",");
                    if(yearSub.length>0){
                        for(String str :yearSub){
                            double[] between =  getYearBetween(str);
                            double begin = between[0];
                            double end = between[1];
                            if(years<=end && years>begin){
                                isFitable=true;
                                break;
                            }
                        }
                    }
                }
                if(!isFitable){
                    iterator.remove();
                }
            }
        }
        Set<String> appointVehicleIdSet = hsmwVehicleList.stream().map(HsmwVehicle::getId).collect(Collectors.toSet());
        if (CollectionUtil.isNotEmpty(appointVehicleIdSet)) {
            List<String> status = new ArrayList<>();
            status.add(CommonConstants.DRIVER_ACCEPT_ORDER);
            Map<String, List<HsmwUserDriver>> vehicleDriverMap = hsmwUserDriverMapper.selectList(Wrappers.lambdaQuery(HsmwUserDriver.class)
                    .in(HsmwUserDriver::getVehicleId, appointVehicleIdSet).in(HsmwUserDriver::getWorkStatus, status))
                    .stream()
                    .peek(System.out::println)
                    .collect(Collectors.groupingBy(HsmwUserDriver::getVehicleId));
            Iterator<HsmwVehicle> iterator1 = hsmwVehicleList.iterator();
            while (iterator1.hasNext()) {
                HsmwVehicle hsmwVehicle = iterator1.next();
                HashMap param = new HashMap();
                param.put("vehicleId", hsmwVehicle.getId());
                param.put("reachTime", dtf.format(hsmwOrderVehicleRequest.getReachTime()));
                if (CollectionUtil.isEmpty(vehicleDriverMap.get(hsmwVehicle.getId()))) {
                    iterator1.remove();
                } else if (hsmwReportService.checkIfHasleavingRecord(param)) {
                    iterator1.remove();
                }
            }
            avaliableVehicles.addAll(hsmwVehicleList);
        }
        return avaliableVehicles;
    }


    //通过需求ID 获取符合该需求的车辆信息 自营 合作 平台 三种类型
    public List<HsmwVehicle> getIdleVehicleListByRequestId(HsmwOrderVehicleRequest hsmwOrderVehicleRequest,String type,HsmwHtnUser createuser,String itemCreateUserCompanyId,HsmwHtnUser itemCreator) {
        LambdaQueryWrapper<HsmwVehicle> lambdaQueryWrapper = Wrappers.lambdaQuery(HsmwVehicle.class);
        List<HsmwVehicle> avaliableVehicles = new ArrayList<>(128);
        if(hsmwOrderVehicleRequest.isFlag()){
            lambdaQueryWrapper.eq(HsmwVehicle::getVehicleType, hsmwOrderVehicleRequest.getVehicleType());
            lambdaQueryWrapper.ne(HsmwVehicle::getVehicleModel, hsmwOrderVehicleRequest.getVehicleModel());
        }else {
            lambdaQueryWrapper.eq(HsmwVehicle::getVehicleModel, hsmwOrderVehicleRequest.getVehicleModel());
            lambdaQueryWrapper.eq(HsmwVehicle::getVehicleType, hsmwOrderVehicleRequest.getVehicleType());
        }
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        List<String> vehicleStatus = new ArrayList<>();
        vehicleStatus.add(CommonConstants.VEHICLE_FREE);
        lambdaQueryWrapper.in(HsmwVehicle::getWorkStatus, vehicleStatus);
        //首先查询出来符合的车辆
        List<HsmwVehicle> hsmwVehicleList=new ArrayList<>();
        //如果是自营的车辆列表那么
        if(CorperateTypeEnum.SELFRUN.getValue().equals(type)){
            lambdaQueryWrapper.eq(HsmwVehicle::getLeasingCompanyId,hsmwOrderVehicleRequest.getLeasingCompanyId());
            hsmwVehicleList = hsmwVehicleService.list(lambdaQueryWrapper);
        }
        if(CorperateTypeEnum.ALL.getValue().equals(type)){
            hsmwVehicleList = hsmwVehicleService.list(lambdaQueryWrapper);
        }
        if(CorperateTypeEnum.CORPERATE.getValue().equals(type)){
            LambdaQueryWrapper<HsmwCorporationCompany> lambdaQueryWrapper1= new LambdaQueryWrapper<HsmwCorporationCompany>();
            if(HtnUserTypeEnum.COMPANY.getValue().equals(createuser.getType())){
                lambdaQueryWrapper1.eq(HsmwCorporationCompany::getCompanyId,createuser.getOwnCompanyId());
            }
            if(HtnUserTypeEnum.CONCRETE.getValue().equals(createuser.getType())){
                lambdaQueryWrapper1.eq(HsmwCorporationCompany::getConcretePlantId,createuser.getOwnCompanyId());
            }
            if(HtnUserTypeEnum.FOREMAN.getValue().equals(createuser.getType())){
                if(HtnUserTypeEnum.COMPANY.getValue().equals(itemCreator.getType())){
                    lambdaQueryWrapper1.eq(HsmwCorporationCompany::getCompanyId,itemCreator.getOwnCompanyId());
                }
                if(HtnUserTypeEnum.CONCRETE.getValue().equals(itemCreator.getType())){
                    lambdaQueryWrapper1.eq(HsmwCorporationCompany::getConcretePlantId,itemCreator.getOwnCompanyId());
                }
            }
            lambdaQueryWrapper1.eq(HsmwCorporationCompany::getCorperateType,CorperateTypeEnum.CORPERATE.getValue());
            List<HsmwCorporationCompany> corporationCompanies = hsmwCorporationCompanyMapper.selectList(lambdaQueryWrapper1);
            if(CollectionUtil.isNotEmpty(corporationCompanies)){
                Set<String> companyIds  =new HashSet<>();
                companyIds  = corporationCompanies.stream().map(HsmwCorporationCompany::getCorperateCompanyId).collect(Collectors.toSet());
                lambdaQueryWrapper.in(HsmwVehicle::getLeasingCompanyId,companyIds);
            }
            //当合作公司的车辆不为空的时候 才会查询合作公司的车辆
            if(CollectionUtil.isNotEmpty(corporationCompanies)){
                hsmwVehicleList = hsmwVehicleService.list(lambdaQueryWrapper);
            }
        }
        if(!CorperateTypeEnum.CORPERATE.getValue().equals(type) && !CorperateTypeEnum.SELFRUN.getValue().equals(type) && !CorperateTypeEnum.ALL.getValue().equals(type)){
            HashMap param =  new HashMap();
            if(HtnUserTypeEnum.FOREMAN.getValue().equals(createuser.getType())){
                param.put("companyId",itemCreator.getOwnCompanyId());
            }else {
                param.put("companyId",createuser.getOwnCompanyId());
            }
            if(hsmwOrderVehicleRequest.isFlag()){
                param.put("vehicleType",hsmwOrderVehicleRequest.getVehicleType());
            }
            hsmwVehicleList=hsmwVehicleService.selectPlateformVehicles(param);
        }
        //首先查询出来符合的车辆
        Set<String> appointVehicleIdSet = hsmwVehicleList.stream().map(HsmwVehicle::getId).collect(Collectors.toSet());
        if (CollectionUtil.isNotEmpty(appointVehicleIdSet)) {
            List<String> status = new ArrayList<>();
            status.add(CommonConstants.DRIVER_ACCEPT_ORDER);
            Map<String, List<HsmwUserDriver>> vehicleDriverMap = hsmwUserDriverMapper.selectList(Wrappers.lambdaQuery(HsmwUserDriver.class)
                    .in(HsmwUserDriver::getVehicleId, appointVehicleIdSet).in(HsmwUserDriver::getWorkStatus, status))
                    .stream()
                    .peek(System.out::println)
                    .collect(Collectors.groupingBy(HsmwUserDriver::getVehicleId));
            Iterator<HsmwVehicle> iterator1 = hsmwVehicleList.iterator();
            while (iterator1.hasNext()) {
                HsmwVehicle hsmwVehicle = iterator1.next();
                HashMap param = new HashMap();
                param.put("vehicleId", hsmwVehicle.getId());
                param.put("reachTime", dtf.format(hsmwOrderVehicleRequest.getReachTime()));
                if (CollectionUtil.isEmpty(vehicleDriverMap.get(hsmwVehicle.getId()))) {
                    iterator1.remove();
                } else if (hsmwReportService.checkIfHasleavingRecord(param)) {
                    iterator1.remove();
                }
            }
            avaliableVehicles.addAll(hsmwVehicleList);
        }
        return avaliableVehicles;
    }

    /**
     * 发布订单
     *
     * @param order
     * @return
     */
    public void publishHsmwOrder(HsmwOrderVO order) {
        //首先判断
        if (StringUtils.isNotBlank(order.getDriverId())) {
            List<HsmwOrderVehicleRequest> requestList = hsmwOrderVehicleRequestService.list(new LambdaQueryWrapper<HsmwOrderVehicleRequest>()
                    .eq(HsmwOrderVehicleRequest::getOrderId, order.getId()));
            HsmwOrderVehicleRequest request = requestList.get(0);
            HsmwUserDriver driver = hsmwUserDriverService.getById(order.getDriverId());
            HsmwDriverUser driverUser = hsmwDriverUserMapper.selectById(driver.getUserId());
            HsmwOrderDistributeInfo info = new HsmwOrderDistributeInfo();
            info.setOrderId(order.getId());
            info.setOrderVehicleRequestId(request.getId());
            info.setDistributeStatus(DistributeStatusEnum.RELEASED.getValue());
            info.setDistributeType(order.getDistributeType());
            info.setVehicleId(driver.getVehicleId());
            info.setDistributeTime(LocalDateTime.now());
            hsmwOrderDistributeInfoService.save(info);
            TencentPushUtils.pushMsg("您有新的订单，请尽快查看 ！", driverUser.getUsername(), "order_status_2");
            HsmwDriverNews news = new HsmwDriverNews();
            news.setMessage("您有新的订单，请尽快查看 ！");
            news.setUserId(driverUser.getId());
            news.setAlreadyRead("0");
            hsmwDriverNewsService.save(news);

            //websocket 实时推送
            WebSocketReturnVO vo = new WebSocketReturnVO();
            order.setOrderVehicleRequestId(request.getId());
            vo.setStatus(WebsocketTypeEnum.NEWORDER.getValue());
            vo.setMessage("您有新的订单，请尽快查看 ！");
            vo.setData(order);
            String returnJson = JSONObject.toJSON(vo).toString();
            webSocket.AppointSending(driverUser.getUsername(), returnJson);
            //新增系统消息
            HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
            hsmwDriverNews.setUserId(driverUser.getId());
            hsmwDriverNews.setMessage("您有新的订单，请尽快查看!");
            hsmwDriverNews.setAlreadyRead("0");
            //该需求的状态改为 已发布
            request.setRequestStatus(DistributeStatusEnum.RELEASED.getValue());
            hsmwOrderVehicleRequestService.updateById(request);
            return;
        }
        //自动派单 ==== 首选查询出来 该订单所有的需求信息
        LocalDateTime reachTime = order.getReachTime();
        java.time.Duration duration = java.time.Duration.between(LocalDateTime.now(), reachTime);
        HsmwItem itemInfo = hsmwItemService.getHsmwItemById(order.getItemId());
        long hours = duration.toHours();
        //如果到车时间小于24 小时 那么立即进行派单
        if (LocalDateTime.now().plusHours(24).isAfter(order.getReachTime())) {
            LambdaQueryWrapper<HsmwOrderVehicleRequest> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(HsmwOrderVehicleRequest::getOrderId, order.getId());
            List<HsmwOrderVehicleRequest> requestList = hsmwOrderVehicleRequestService.list(lambdaQueryWrapper);
            //分别对每一个需求进行派单
            requestList.stream().forEach(hsmwOrderVehicleRequest -> {
                List<HsmwVehicle> aviliableVehicles = new ArrayList<>();
                //	查询出来符合需求的车辆信息
                hsmwOrderVehicleRequest.setLeasingCompanyId(itemInfo.getVehicleUnitId());
                GetRequestVehicleListDTO vihicle = getRequestVehicleListByRequestId(hsmwOrderVehicleRequest);
                //当查询出的符合需求的车辆的信息为空的时候，不进行派单
                if (StringUtils.isListNotNull(vihicle.getHsmwVehicleList())) {
                    String imeiStrs = "";
                    String vehicleIds = "";
                    for (HsmwVehicle vehicle : vihicle.getHsmwVehicleList()) {
                        if (StringUtils.isNotBlank(vehicle.getImeiNum())) {
                            imeiStrs += ("," + vehicle.getImeiNum());
                            vehicleIds += ("," + vehicle.getIdentifyingCode());
                        }
                    }
                    List<HsmwOrderDistributeInfo> distributeInfos = new ArrayList<>();
                    //chaxun
                    List<GpsInfoEntity> gpsInfoEntities = new ArrayList<>();
                    if (StringUtils.isNotBlank(imeiStrs)) {
                        gpsInfoEntities = GaoDeInfoUtils.getVehicleGpsLocate(imeiStrs,vehicleIds);
                    }
                    if (StringUtils.isListNotNull(vihicle.getHsmwVehicleList())) {
                        List<GpsInfoEntity> finalGpsInfoEntities = gpsInfoEntities;
                        vihicle.getHsmwVehicleList().stream().forEach(hsmwVehicle -> {
                            //查询距离时间
                            String vehicleLocalteInfo = null;
                            String destinationLocateInfo = order.getLng() + "," + order.getLat();
                            if (finalGpsInfoEntities.size() > 0) {
                                for (GpsInfoEntity entity : finalGpsInfoEntities) {
                                    if (entity.getDeviceId().equals(hsmwVehicle.getImeiNum()) || StringUtils.equals(entity.getDeviceId(),hsmwVehicle.getIdentifyingCode())) {
                                        if (StringUtils.isNotBlank(entity.getGpsLat())) {
                                            vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                                        }
                                        break;
                                    }
                                }
                                if (StringUtils.isBlank(vehicleLocalteInfo)) {
                                    vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
                                }
                            }
                            if (StringUtils.isBlank(vehicleLocalteInfo)) {
                                vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
                            }
                            if (StringUtils.isNotBlank(vehicleLocalteInfo)) {
                                HashMap calculateParam = new HashMap();
                                calculateParam.put("origin", vehicleLocalteInfo);
                                calculateParam.put("destination", destinationLocateInfo);
                                Long durationTime = GaoDeInfoUtils.calculateDistanceTime(calculateParam);
                                long sconds = duration.toMillis() / 1000;
                                if ((float) sconds / 3600 >= ((float) durationTime / 3600)) {
                                    aviliableVehicles.add(hsmwVehicle);
                                }
                            }
                        });
                    }
                    //经过筛选，如果没有合适的司机就不进行派单
                    if (StringUtils.isListNotNull(aviliableVehicles)) {
                        //针对筛选后的可以派单司机进行派单
                        aviliableVehicles.stream().forEach(hsmwVehicle -> {
                            HsmwOrderDistributeInfo info = new HsmwOrderDistributeInfo();

                            if (CommonConstants.VEHICLE_FREE.equals(hsmwVehicle.getWorkStatus())) {
                                info.setHideOrder(CommonConstants.ORDER_DISPLAY);
                            } else {
                                info.setHideOrder(CommonConstants.ORDER_HIDE);
                            }
                            info.setOrderId(order.getId());
                            info.setOrderVehicleRequestId(hsmwOrderVehicleRequest.getId());
                            info.setDistributeStatus(DistributeStatusEnum.RELEASED.getValue());
                            info.setDistributeType(order.getDistributeType());
                            info.setVehicleId(hsmwVehicle.getId());
                            info.setDistributeTime(LocalDateTime.now());
                            distributeInfos.add(info);
                        });
                        hsmwOrderDistributeInfoService.saveBatch(distributeInfos);
                        //查询 可用的车辆对应的司机列表
                        List<HsmwUserDriver> hsmwUserDriverList = hsmwUserDriverMapper.selectList(Wrappers.lambdaQuery(HsmwUserDriver.class).eq(HsmwUserDriver::getWorkStatus, CommonConstants.DRIVER_ACCEPT_ORDER).
                                in(HsmwUserDriver::getVehicleId, aviliableVehicles.stream().map(HsmwVehicle::getId).
                                        collect(Collectors.toSet())));
                        ArrayList<HsmwDriverNews> hsmwDriverNewsArrayList = Lists.newArrayList();
                        List<HsmwUserDriver> avilableDriverList = new ArrayList<>();
                        //筛选出 在接单中的司机进行推送
                        hsmwUserDriverList.stream().forEach(hsmwUserDriver -> {
                            if (CommonConstants.DRIVER_ACCEPT_ORDER.equals(hsmwUserDriver.getWorkStatus())) {
                                avilableDriverList.add(hsmwUserDriver);
                            }
                        });
                        //如果该需求有合适的车 那么就把该需求的状态改为 已发布
                        hsmwOrderVehicleRequest.setRequestStatus(DistributeStatusEnum.RELEASED.getValue());
                        ///接单中的司机进行推送
                        if (CollectionUtil.isNotEmpty(avilableDriverList)) {
                            //app离线推送消息
                            List<String> userIdList = avilableDriverList.stream().map(HsmwUserDriver::getUserId).collect(Collectors.toList());
                            List<HsmwDriverUser> hsmwUsers = hsmwDriverUserService.list(Wrappers.lambdaQuery(HsmwDriverUser.class).in(HsmwDriverUser::getId, userIdList));
                            List<String> hsmwUserNames = new ArrayList<>();
                            Optional.ofNullable(hsmwUsers).map(List::stream)
                                    .orElseGet(Stream::empty)
                                    .map(HsmwUser::getUsername)
                                    .filter(x -> StrUtil.isNotBlank(x))
                                    .forEach(username -> {
                                        hsmwUserNames.add(username);
                                        TencentPushUtils.pushMsg("您有新的订单，请尽快查看 ！", username, "order_status_2");
                                    });
                            //websocket 实时推送
                            WebSocketReturnVO vo = new WebSocketReturnVO();
                            order.setOrderVehicleRequestId(hsmwOrderVehicleRequest.getId());
                            vo.setStatus(WebsocketTypeEnum.NEWORDER.getValue());
                            vo.setMessage("您有新的订单，请尽快查看 ！");
                            vo.setData(order);
                            String returnJson = JSONObject.toJSON(vo).toString();
                            webSocket.GroupSending(returnJson, hsmwUserNames);
                            //新增系统消息
                            hsmwUserDriverList.stream().forEach(hsmwUserDriver -> {
                                HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                                hsmwDriverNews.setUserId(hsmwUserDriver.getUserId());
                                hsmwDriverNews.setMessage("您有新的订单，请尽快查看!");
                                hsmwDriverNews.setAlreadyRead("0");
                                hsmwDriverNewsArrayList.add(hsmwDriverNews);
                            });
                            hsmwDriverNewsService.saveBatch(hsmwDriverNewsArrayList);
                        }
                    }
                } else {
                    //如果该需求有合适的车 那么就把该需求的状态改为 待发布
                    hsmwOrderVehicleRequest.setRequestStatus(DistributeStatusEnum.UNRELEASE.getValue());
                }
                hsmwOrderVehicleRequestService.updateById(hsmwOrderVehicleRequest);
            });
            //将订单的发布时间赋值
            order.setPublishTime(LocalDateTime.now());
            hsmwOrderMapper.updateById(order);
        }
    }


    public void cancelHsmwOrder(String orderId) {
        HsmwOrder hsmwOrder = hsmwOrderMapper.selectById(orderId);
        hsmwOrder.setOrderStatus(OrderStatusEnum.CANCELED.getValue());
        hsmwOrderMapper.updateById(hsmwOrder);
        List<HsmwOrderVehicleRequest> hsmwOrderVehicleRequestList = hsmwOrderVehicleRequestService.list(Wrappers.lambdaQuery(HsmwOrderVehicleRequest.class).eq(HsmwOrderVehicleRequest::getOrderId, orderId));
        hsmwOrderVehicleRequestList.forEach(x -> x.setRequestStatus(OrderStatusEnum.CANCELED.getValue()));
        hsmwOrderVehicleRequestService.updateBatchById(hsmwOrderVehicleRequestList);
        List<HsmwOrderVehicleRelation> hsmwOrderVehicleRelationList = hsmwOrderVehicleRelationService.list(Wrappers.lambdaQuery(HsmwOrderVehicleRelation.class).eq(HsmwOrderVehicleRelation::getOrderId, orderId));
        hsmwOrderVehicleRelationList.stream()
                .forEach(hsmwOrderVehicleRelation -> {
                    hsmwOrderVehicleRelation.setEndTime(LocalDateTime.now());
                    hsmwOrderVehicleRelation.setOrderStatus(OrderStatusEnum.CANCELED.getValue());
                });
        hsmwOrderVehicleRelationService.updateBatchById(hsmwOrderVehicleRelationList);
        Set<String> vehicleIdSet = hsmwOrderVehicleRelationList.stream().map(HsmwOrderVehicleRelation::getVehicleId).collect(Collectors.toSet());
        List<HsmwVehicle> hsmwVehicleList = hsmwVehicleMapper.selectBatchIds(vehicleIdSet);
        hsmwVehicleList.forEach(hsmwVehicle -> {
            hsmwVehicle.setWorkStatus(CommonConstants.VEHICLE_FREE);
        });
        hsmwVehicleService.updateBatchById(hsmwVehicleList);
        List<HsmwUserDriver> hsmwUserDriverList = hsmwUserDriverMapper.selectList(Wrappers.lambdaQuery(HsmwUserDriver.class).in(HsmwUserDriver::getVehicleId, hsmwVehicleList));
        hsmwUserDriverList.forEach(hsmwUserDriver -> {
            hsmwUserDriver.setWorkStatus(CommonConstants.DRIVER_FREE);
        });
        hsmwUserDriverService.updateBatchById(hsmwUserDriverList);
    }

    public void correctVolume(String id, String volume) {
        HsmwOrderVehicleRelation hsmwOrderVehicleRelation = hsmwOrderVehicleRelationService.getById(id);
        hsmwOrderVehicleRelation.setDriverVolume(volume);
        hsmwOrderVehicleRelationService.save(hsmwOrderVehicleRelation);
    }


    public List<PMOrderCountVO> selectOrderListByParam(HashMap param) {
        return hsmwOrderVehicleRelationMapper.selectOrderListByParam(param);

    }

    public List<PMGoingOrderVO> selectGOingOrderListByParam(HashMap param) {
        return hsmwOrderVehicleRelationMapper.selectGOingOrderListByParam(param);

    }

    public List<ForemanCountVO> getFormanCountInfo(HashMap param) {
        return hsmwOrderMapper.getFormanCountInfo(param);
    }

    public HashMap concreteCountInfo(String staticsType, HashMap param) {
        HashMap res = new HashMap();
        Map<LocalDate, List<ForemanCountVO>> result = new HashMap<LocalDate, List<ForemanCountVO>>();
        List<ForemanCountVO> resList = new ArrayList<ForemanCountVO>();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        if (CommonConstants.DEFAULT_STATISCICS.equals(staticsType)) {
            LocalDate now = LocalDate.now().plusDays(1);
            LocalDate firstWeekDay = now.plusDays(-7);
            param.put("startTime", firstWeekDay);
            param.put("endTime", now);

            List<ConcrateCountDTO> weekList = new ArrayList<>();
            for (int i = 0; i < 7; i++) {
                ConcrateCountDTO dto = new ConcrateCountDTO();
                dto.setStaticsTime(df.format(firstWeekDay.plusDays(i)));
                weekList.add(dto);
            }
            List<ConcrateCountDTO> defaultList = hsmwOrderMapper.concreteDefaultCountInfo(param);
            for (ConcrateCountDTO dts : weekList) {
                for (ConcrateCountDTO dt : defaultList) {
                    if (dts.getStaticsTime().equals(dt.getStaticsTime())) {
                        dts.setVolumeCount(dt.getVolumeCount());
                        dts.setWeek(dt.getWeek());
                    }
                }
            }
            res.put("list", weekList);
            return res;
        }

        if (CommonConstants.DAY_STATISCICS.equals(staticsType)) {
            List<ConcrateCountDTO> days = hsmwOrderMapper.concreteDefaultCountInfo(param);
            res.put("list", days);
            return res;
        }
        if (CommonConstants.MONTH_STATISCICS.equals(staticsType)) {
            List<ConcrateCountDTO> monList = hsmwOrderMapper.concreteMonthCountInfo(param);
            res.put("list", monList);
            return res;
        }
        return new HashMap();

    }

    public List<ContructionPosionAndbatchPlantVO> queryRecentsAddresslist(HashMap param) {
        return hsmwOrderMapper.queryRecentsAddresslist(param);
    }

    public List<ContructionPosionAndbatchPlantVO> queryRecentsPlantlist(HashMap param) {
        return hsmwOrderMapper.queryRecentsPlantlist(param);
    }

    public List<ForcemanCurrentOrderDTO> selectOrderListByCreateUser(HashMap param) {
        return hsmwOrderMapper.selectOrderListByCreateUser(param);
    }

    public List<PMGoingOrderVO> selectOrderProcessByOrderId(HashMap param) {
        return hsmwOrderMapper.selectOrderProcessByOrderId(param);
    }

    public List<PMOrderCountVO> selectForemanOrderListByParam(HashMap param) {
        return hsmwOrderMapper.selectForemanOrderListByParam(param);
    }

    public HashMap getOrderDictInfo() {
        LambdaQueryWrapper<HsmwDictData> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        List<String> dicTypes = new ArrayList<>();
        dicTypes.add("sys_concrete_type");
        dicTypes.add("sys_slump_type");
        dicTypes.add("sys_vehicle_model");
        dicTypes.add("sys_xb_type");
        dicTypes.add("sys_czdb_type");
        dicTypes.add("sys_tsdb_type");

        dicTypes.add("sys_db_type");
        dicTypes.add("sys_xsb_type");

        lambdaQueryWrapper.in(HsmwDictData::getDictType, dicTypes);

        lambdaQueryWrapper.orderByAsc(HsmwDictData::getDictType).orderByAsc(HsmwDictData::getDictSort);
        List<HsmwDictData> list = hsmwDictDataService.getOrderDicDate(lambdaQueryWrapper);
        List<DictDataVO> dictDataVOS = new ArrayList<>();

        DictDataVO concreteTypeVo = new DictDataVO();
        concreteTypeVo.setDicType("sys_concrete_type");
        concreteTypeVo.setDictnNeme("混凝土标号");
        List<HsmwDictData> concreteTypeList = new ArrayList<HsmwDictData>();

        DictDataVO slumpTypeVo = new DictDataVO();
        slumpTypeVo.setDicType("sys_slump_type");
        slumpTypeVo.setDictnNeme("塌落度");
        List<HsmwDictData> slumpTypeList = new ArrayList<HsmwDictData>();


        DictDataVO vehicleModelVO = new DictDataVO();
        vehicleModelVO.setDicType("sys_vehicle_model");
        vehicleModelVO.setDictnNeme("车辆类型");
        List<HsmwDictData> vehicleModelList = new ArrayList<HsmwDictData>();

        DictDataVO XBTypeVo = new DictDataVO();
        XBTypeVo.setDicType("sys_xb_type");
        XBTypeVo.setDictnNeme("象泵型号");
        List<HsmwDictData> XBTypeList = new ArrayList<HsmwDictData>();


        DictDataVO CZDBTypeVo = new DictDataVO();
        CZDBTypeVo.setDicType("sys_czdb_type");
        CZDBTypeVo.setDictnNeme("车载地泵型号");
        List<HsmwDictData> CZDBTypeList = new ArrayList<HsmwDictData>();


        DictDataVO TSDBTypeVo = new DictDataVO();
        TSDBTypeVo.setDicType("sys_tsdb_type");
        TSDBTypeVo.setDictnNeme("拖式地泵");
        List<HsmwDictData> TSDBTypeList = new ArrayList<HsmwDictData>();

        DictDataVO DBTypeVo = new DictDataVO();
        DBTypeVo.setDicType("sys_db_type");
        DBTypeVo.setDictnNeme("电泵型号");
        List<HsmwDictData> DBTypeList = new ArrayList<HsmwDictData>();

        DictDataVO XSBTypeVo = new DictDataVO();
        XSBTypeVo.setDicType("sys_xsb_type");
        XSBTypeVo.setDictnNeme("细石泵型号");
        List<HsmwDictData> XSBTypeList = new ArrayList<HsmwDictData>();

        for (HsmwDictData data : list) {
            if (data.getDictType().equals("sys_concrete_type")) {
                concreteTypeList.add(data);
            }
            if (data.getDictType().equals("sys_slump_type")) {
                slumpTypeList.add(data);

            }
            if (data.getDictType().equals("sys_vehicle_model")) {
                vehicleModelList.add(data);
            }

            if (data.getDictType().equals("sys_xb_type")) {
                XBTypeList.add(data);
            }

            if (data.getDictType().equals("sys_czdb_type")) {
                CZDBTypeList.add(data);
            }


            if (data.getDictType().equals("sys_tsdb_type")) {
                TSDBTypeList.add(data);
            }


            if (data.getDictType().equals("sys_db_type")) {
                DBTypeList.add(data);
            }


            if (data.getDictType().equals("sys_xsb_type")) {
                XSBTypeList.add(data);
            }

        }
        concreteTypeVo.setItemList(concreteTypeList);
        slumpTypeVo.setItemList(slumpTypeList);
        vehicleModelVO.setItemList(vehicleModelList);
        XBTypeVo.setItemList(XBTypeList);
        CZDBTypeVo.setItemList(CZDBTypeList);
        TSDBTypeVo.setItemList(TSDBTypeList);
        DBTypeVo.setItemList(DBTypeList);
        XSBTypeVo.setItemList(XSBTypeList);

        dictDataVOS.add(concreteTypeVo);
        dictDataVOS.add(slumpTypeVo);
        dictDataVOS.add(vehicleModelVO);
        dictDataVOS.add(XBTypeVo);
        dictDataVOS.add(CZDBTypeVo);
        dictDataVOS.add(TSDBTypeVo);
        dictDataVOS.add(DBTypeVo);
        dictDataVOS.add(XSBTypeVo);
        HashMap result = new HashMap();
        result.put("dictData", dictDataVOS);
        return result;

    }

    public List<HsmwOrderVehicleRequest> getUnCompletePublish() {
        return hsmwOrderMapper.getUnCompletePublish();
    }

    public List<PMGoingOrderVO> selectOrderProcessByVehicleId(HashMap param) {
        return hsmwOrderMapper.selectOrderProcessByVehicleId(param);
    }

    public List<HsmwOrder> selectOrderByVehicleId(HashMap param) {
        return hsmwOrderMapper.selectOrderByVehicleId(param);
    }

    public void publishUnCompleteOrder() {
        // 首选筛选出 时间在24 小时之内的订单。
        // 然后查询这些request 的剩余接单数量是否大于0 如果是大于0  则
        //

    }


    public IPage<HsmwOrder> findOrderListByStatus(IPage page, HsmwOrder hsmwOrder) {
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        if (hsmwOrder.getReachTime() != null) {
            String strDate2 = dtf2.format(hsmwOrder.getReachTime());
            hsmwOrder.setQueryReachTime(strDate2);
        }
        if (hsmwOrder.getEndTime() != null) {
            String strDate2 = dtf2.format(hsmwOrder.getEndTime());
            hsmwOrder.setQueryEndTime(strDate2);
        }
        IPage<HsmwOrder> orderIPage = hsmwOrderMapper.findOrderListByStatus(page, hsmwOrder);
        return orderIPage;
    }

/*    public Map findVehicleInfoByOrderSn(String orderSn, String status) {
        Map map = new HashMap();
        switch (status) {
            case "wait":
                List<OrderAndVehicleVo> orderAndVehicleVo = hsmwOrderMapper.findWaitVehicleInfoByOrderSn(orderSn);
                for (OrderAndVehicleVo andVehicleVo : orderAndVehicleVo) {
                    List<CountVO> countVOS = hsmwOrderMapper.selctVehicleCount(andVehicleVo.getVehicleType(), andVehicleVo.getVehicleModel());
                    Long sumCount = hsmwOrderMapper.selectSumCount(andVehicleVo.getVehicleType(), andVehicleVo.getVehicleModel());
                    andVehicleVo.setCountVOS(countVOS);
                    andVehicleVo.setSumCount(sumCount);
                }
                map.put("orderAndVehicleVo", orderAndVehicleVo);
                break;
            case "hand":
                List<OrderAndVehicleVo> handOrderAndVehicleVo = hsmwOrderMapper.findWaitVehicleInfoByOrderSn(orderSn);

                for (OrderAndVehicleVo andVehicleVo : handOrderAndVehicleVo) {
                    Long count = hsmwOrderMapper.findOdvList(orderSn, andVehicleVo.getVehicleModel(), andVehicleVo.getVehicleType());
                    List<HandOrderDriverDetailInfoVO> orderDriverDetailInfoVOS = hsmwOrderMapper.findDriverInfoByOrderSn(orderSn, andVehicleVo.getVehicleModel(), andVehicleVo.getVehicleType());
                    for (HandOrderDriverDetailInfoVO orderDriverDetailInfoVO : orderDriverDetailInfoVOS) {
                        String imeiNum = orderDriverDetailInfoVO.getImeiNum();
                        if (StringUtils.isNotBlank(imeiNum)) {
                            GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(imeiNum);
                            if (StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
                                orderDriverDetailInfoVO.setMobileLocate(entity.getGpsLon() + "," + entity.getGpsLat());
                            }
                        }
                    }
                    andVehicleVo.setHandOrderDriverDetailInfoVOS(orderDriverDetailInfoVOS);
                    andVehicleVo.setReceivedDriCount(count);
                }
                map.put("handOrderAndVehicleVo", handOrderAndVehicleVo);
                break;
            case "pub":
                List<OrderAndVehicleVo> pubOrderAndVehicleVo = hsmwOrderMapper.findWaitVehicleInfoByOrderSn(orderSn);
                for (OrderAndVehicleVo andVehicleVo : pubOrderAndVehicleVo) {
                    Long count = hsmwOrderMapper.findOdvList(orderSn, andVehicleVo.getVehicleModel(), andVehicleVo.getVehicleType());
                    List<HandOrderDriverDetailInfoVO> orderDriverDetailInfoVO = hsmwOrderMapper.findDriverRequestInfoByOrderSn(andVehicleVo.getRequestId(), andVehicleVo.getVehicleModel(), andVehicleVo.getVehicleType());
                    List<DriverInfo> driverInfos = hsmwOrderMapper.findIdleVehiclesInfo(andVehicleVo.getVehicleModel(), andVehicleVo.getVehicleType());
                    andVehicleVo.setHandOrderDriverDetailInfoVOS(orderDriverDetailInfoVO);
                    andVehicleVo.setDriverInfos(driverInfos);
                    andVehicleVo.setReceivedDriCount(count);
                }
                map.put("pubOrderAndVehicleVo", pubOrderAndVehicleVo); //备忘录信息
                break;
        }
        return map;
    }*/


    public void saveOrder(OrderCreateVO orderCreateVO, HsmwHtnUser hsmwUser) {
        String identifyNum = CommonUtils.generateOrderdentifyNum();

        HsmwItem hsmwItem = hsmwItemService.getHsmwItemById(hsmwUser.getItemId());
        orderCreateVO.setCreateName(hsmwUser.getName());
        orderCreateVO.setCreateUser(hsmwUser.getId());
        orderCreateVO.setItemId(hsmwItem.getId());
        orderCreateVO.setIdentityNum(identifyNum);
        orderCreateVO.setConstructionUnitName(hsmwItem.getConstructionUnitName());
        //获取当前用户的信息
        LoginUser currentUser = currentHsmwUserUtils.getCurrentUserInfo();
        orderCreateVO.setOrderSn(RandomUtil.randomUUID());
        orderCreateVO.setCreateName(currentUser.getName());
        orderCreateVO.setCreateUser(currentUser.getId());
        orderCreateVO.setItemName(hsmwItem.getName());
        if (StringUtils.isBlank(hsmwItem.getLng()) && StringUtils.isBlank(hsmwItem.getLng())) {
            orderCreateVO.setLng(hsmwItem.getLng());
            orderCreateVO.setLat(hsmwItem.getLat());
        }
        try {
            orderCreateVO.setCreateTime(LocalDateTime.now());
            orderCreateVO.setOrderStatus(OrderStatusEnum.UNRECEIVED.getValue());
            save(orderCreateVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (CollectionUtil.isNotEmpty(orderCreateVO.getPicList())) {
            List<HsmwPicture> pictures = new ArrayList<>();
            List<HashMap> picList = orderCreateVO.getPicList();
            if (null != picList && picList.size() > 0) {
                for (HashMap<String, String> pic : picList) {
                    HsmwPicture temp = new HsmwPicture();
                    temp.setPicPath(pic.get("picPath"));
                    temp.setPicRealPath(pic.get("realPath"));
                    temp.setOrderId(orderCreateVO.getId());
                    temp.setCreateTime(LocalDateTime.now());
                    temp.setPicType(PicTypeEnum.POSITION_PUMP.getValue());
                    pictures.add(temp);
                }
            }
            hsmwPictureService.saveBatch(pictures);
        }
    }


    //将订单的信息 对选中的车辆进行发布 进行发布
    public void publishOrderToVehicles(OrderCreateVO orderCreateVO) {
        OrderCreateVO createVO = orderCreateVO;
        createVO.setIdleVehicleVos(new ArrayList<>());
        List<IdleVehicleVo> idleVehicleVos = orderCreateVO.getIdleVehicleVos();
        idleVehicleVos.stream().forEach(idleVehicleVo -> {
            HsmwOrderDistributeInfo info = new HsmwOrderDistributeInfo();
		/*	info.setVehicleType(orderCreateVO.getVehicleType());
			info.setVehicleModel(orderCreateVO.getVehicleModel());*/
            info.setOrderId(orderCreateVO.getId());
            info.setDistributeStatus(DistributeStatusEnum.RELEASED.getValue());
            info.setVehicleId(idleVehicleVo.getVehicleId());
            info.setDistributeTime(LocalDateTime.now());
            hsmwOrderDistributeInfoService.save(info);
            idleVehicleVo.getDriverCountVOS().stream().forEach(driverCountVO -> {
                TencentPushUtils.pushMsg("您有新的订单，请尽快查看 ！", driverCountVO.getDriverTelphoneNum(), "order_status_2");
                //websocket 实时推送
                WebSocketReturnVO vo = new WebSocketReturnVO();
                vo.setStatus(WebsocketTypeEnum.NEWORDER.getValue());
                vo.setMessage("您有新的订单，请尽快查看 ！");
                vo.setData(createVO);
                String returnJson = JSONObject.toJSON(vo).toString();
                webSocket.AppointSending(driverCountVO.getDriverTelphoneNum(), returnJson);
                //新增系统消息
                HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                hsmwDriverNews.setUserId(driverCountVO.getUserId());
                hsmwDriverNews.setMessage("您有新的订单，请尽快查看!");
                hsmwDriverNews.setAlreadyRead("0");
                //该需求的状态改为 已发布
            });
        });
    }
/*
    //2.0 床
    public DataResponse createOrderInfo(OrderCreateVO orderCreateVO) {
        String orderId = CommonUtils.generateId(orderCreateVO);
        orderCreateVO.setId(orderId);
        //新版的创建订单 2.0
        //保存订单信息
        LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();

        saveOrder(orderCreateVO, hsmwUser);
        //保存订单信息后 将订单的信息 对选中的车辆进行发布 进行发布
        publishOrderToVehicles(orderCreateVO);
        return new DataResponse();
    }*/

    public List<CurrentOrderInfoVO> getGoingOrderListByParam(HashMap param) {
        return hsmwOrderVehicleRelationMapper.getGoingOrderListByParam(param);
    }


    public List<DriverOrderInfoVO> getOrderListByParam(HashMap param) {
        return hsmwOrderVehicleRelationMapper.getOrderListByParam(param);
    }

    public List<IdleVehicleVo> retailFindOrderStatusList(String param, String companyId, String id) {
        List<IdleVehicleVo> idleVehicleVos = hsmwOrderMapper.retailFindOrderStatusList(param, companyId, id);
        for (IdleVehicleVo idleVehicleVo : idleVehicleVos) {
            String vehicleId = idleVehicleVo.getVehicleId();
            String orderId = idleVehicleVo.getOrderId();
            if(StringUtils.equals("1",param)){
                List<DriverCountVO> driverCountVO = hsmwOrderMapper.findUserDriverListBYVehicleId(vehicleId);
                idleVehicleVo.setDriverCountVOS(driverCountVO);
            }
            if(StringUtils.equals("2",param)){
                List<DriverCountVO> driverCountVO = hsmwOrderMapper.findUserDriverListByOrderId(orderId);
                idleVehicleVo.setDriverCountVOS(driverCountVO);
            }
        }

        return idleVehicleVos;
    }
    public IPage<HtnOrderInfoVO> selectOrderStatusList(IPage page,String param, String companyId, String id,String queryParam ,LocalDateTime startTime,LocalDateTime endTime) {
        IPage<HtnOrderInfoVO>  htnOrderInfoVOS = hsmwOrderMapper.selectOrderInfoListByParam(page,param, companyId, id,queryParam,startTime,endTime);
        List<HtnOrderInfoVO> records = htnOrderInfoVOS.getRecords();
        if(CollectionUtil.isNotEmpty(records))
            for (HtnOrderInfoVO idleVehicleVo : records) {
                List<HtnPumpOrderDetailVo> orderInfoList = idleVehicleVo.getOrderInfoList();
                if(CollectionUtil.isNotEmpty(orderInfoList)){
                    for(HtnPumpOrderDetailVo vo :orderInfoList){
                        String  orderId = vo.getOrderId();
                        String vehicleId = vo.getVehicleId();
                        if(StringUtils.isNotBlank(vehicleId)){
                            if(StringUtils.isNotNull(vo.getCollectFlag()) && vo.getCollectFlag()>0){
                                vo.setCollectFlag(1);
                            }else {
                                vo.setCollectFlag(0);
                            }
                            if(StringUtils.equals("1",param)){
                                List<DriverCountVO> driverCountVOS = hsmwOrderMapper.findUserDriverListBYVehicleId(vehicleId);
                                if(CollectionUtil.isNotEmpty(driverCountVOS)){
                                    driverCountVOS.stream().forEach(driverCountVO -> {
                                        HsmwForcemanEvaluate forcemanEvaluate = hsmwForcemanEvaluateService.getOne(new LambdaQueryWrapper<HsmwForcemanEvaluate>().eq(HsmwForcemanEvaluate::getDriverId, driverCountVO.getDriverId()).eq(HsmwForcemanEvaluate::getRelationId,vo.getRelationId()));
                                        driverCountVO.setHsmwForcemanEvaluate(forcemanEvaluate);
                                    });
                                }
                                vo.setDriverCountVOS(driverCountVOS);
                            }
                            if(StringUtils.equals("2",param)){
                                HashMap params  = new HashMap();
                                params.put("relationId",vo.getRelationId());
                                List<DriverCountVO> driverCountVOS = hsmwOrderMapper.findDriverRecordByParam(params);
                                if(CollectionUtil.isEmpty(driverCountVOS)){
                                    driverCountVOS=hsmwOrderMapper.findUserDriverListByParam(params);
                                }
                                if(CollectionUtil.isNotEmpty(driverCountVOS)){
                                    driverCountVOS.stream().forEach(driverCountVO -> {
                                        if(StringUtils.isNotNull(driverCountVO)){
                                            HsmwForcemanEvaluate forcemanEvaluate = hsmwForcemanEvaluateService.getOne(new LambdaQueryWrapper<HsmwForcemanEvaluate>().eq(HsmwForcemanEvaluate::getDriverId, driverCountVO.getDriverId()).eq(HsmwForcemanEvaluate::getRelationId,vo.getRelationId()));
                                            driverCountVO.setHsmwForcemanEvaluate(forcemanEvaluate);
                                        }
                                    });
                                }
                                vo.setDriverCountVOS(driverCountVOS);
                            }
                            if(StringUtils.equals("3",param)){
                                HashMap params  = new HashMap();
                                params.put("relationId",vo.getRelationId());
                                List<DriverCountVO> driverCountVOS = hsmwOrderMapper.findDriverRecordByParam(params);
                                if(CollectionUtil.isNotEmpty(driverCountVOS)){
                                    driverCountVOS.stream().forEach(driverCountVO -> {
                                        HsmwForcemanEvaluate forcemanEvaluate = hsmwForcemanEvaluateService.getOne(new LambdaQueryWrapper<HsmwForcemanEvaluate>().eq(HsmwForcemanEvaluate::getDriverId, driverCountVO.getDriverId()).eq(HsmwForcemanEvaluate::getRelationId,vo.getRelationId()));
                                        driverCountVO.setHsmwForcemanEvaluate(forcemanEvaluate);
                                    });
                                }

                                vo.setDriverCountVOS(driverCountVOS);
                            }
                        }
                        HashMap params = new HashMap();
                        params.put("orderId",orderId);
                        params.put("requestId",vo.getRequestId());
                        Integer count = hsmwOrderMapper.selectAvaliableCount(params);
                        vo.setAvaliableCount(count);
                        vo.setHsmwConstructionPositionList(idleVehicleVo.getHsmwConstructionPositionList());
                        if(OrderTypeEnum.CONCRETE_ORDER.getValue().equals(vo.getOrderType())){
                            //查询有混凝土记录那么 直接查询如果 没有记录 就查询记录并 查询出来
                            List<HsmwConcreteOperate> hsmwConcreteOperates = null;
                            List<HsmwConcreteOperate> concreteOperates = hsmwConcreteOperateService.list(new LambdaQueryWrapper<HsmwConcreteOperate>()
                                    .eq(HsmwConcreteOperate::getOrderId, vo.getOrderId()));
                            if (CollectionUtil.isEmpty(concreteOperates)) {
                                //查询出全部的混凝土的标号的类型
                                List<HsmwConcreteInfo> hsmwConcreteInfoList = hsmwConcreteInfoMapper.selectConcretelist(params);
                                hsmwConcreteInfoList.stream().forEach(hsmwConcreteInfo -> {
                                    HsmwConcreteOperate operate = new HsmwConcreteOperate();
                                    operate.setOrderId(vo.getOrderId());
                                    operate.setConcreteNum(hsmwConcreteInfo.getConcreteNum());
                                    operate.setExpectVolume(hsmwConcreteInfo.getExpectVolume());
                                    operate.setSlump(hsmwConcreteInfo.getSlump());
                                    operate.setIncreaseandOrDecrease(hsmwConcreteInfo.getIncreaseandOrDecrease());
                                    // operate.setOperUser(hsmwUser.getId());
                                    hsmwConcreteOperateMapper.insert(operate);
                                });
                                hsmwConcreteOperates = hsmwConcreteOperateMapper.selectList(new LambdaQueryWrapper<HsmwConcreteOperate>()
                                        .eq(HsmwConcreteOperate::getOrderId, vo.getOrderId()));
                            } else {
                                hsmwConcreteOperates = concreteOperates;
                            }
                            vo.setHsmwConcreteOperates(hsmwConcreteOperates);
                        }
                        // 查询调度备注信息
                        List<HsmwDispatchOrderRemark> dispatchOrderRemarks = hsmwDispatchOrderRemarkMapper.selectList(new LambdaQueryWrapper<HsmwDispatchOrderRemark>()
                                .eq(HsmwDispatchOrderRemark::getRequestId,vo.getRequestId()));
                        vo.setDispatchOrderRemarks(dispatchOrderRemarks);

                    }
                }
                idleVehicleVo.setHsmwConstructionPositionList(new ArrayList<>());
            }
        htnOrderInfoVOS.setRecords(records);
        return htnOrderInfoVOS;
    }

    public IPage<HtnPumpOrderDetailVo> selectConcreteOrderList(IPage page,String param, String companyId, String id) {
        IPage<HtnPumpOrderDetailVo>  htnOrderInfoVOS = hsmwOrderMapper.selectConcreteOrderInfoListByParam(page,param, companyId, id);
        List<HtnPumpOrderDetailVo> htnPumpOrderDetailVos = htnOrderInfoVOS.getRecords();
        if(CollectionUtil.isNotEmpty(htnPumpOrderDetailVos)){
            htnPumpOrderDetailVos.stream().forEach(htnOrderInfoVO ->{
                HashMap params = new HashMap();
                params.put("orderId",htnOrderInfoVO.getOrderId());
                List<HsmwConstructionPosition > ps= hsmwOrderMapper.selectPositionsByOrderId(params);
                htnOrderInfoVO.setHsmwConstructionPositionList(ps);

                //查询有混凝土记录那么 直接查询如果 没有记录 就查询记录并 查询出来
                List<HsmwConcreteOperate> hsmwConcreteOperates = null;
                List<HsmwConcreteOperate> concreteOperates = hsmwConcreteOperateService.list(new LambdaQueryWrapper<HsmwConcreteOperate>()
                        .eq(HsmwConcreteOperate::getOrderId, htnOrderInfoVO.getOrderId()));
                if (CollectionUtil.isEmpty(concreteOperates)) {
                    //查询出全部的混凝土的标号的类型
                    List<HsmwConcreteInfo> hsmwConcreteInfoList = hsmwConcreteInfoMapper.selectConcretelist(params);
                    hsmwConcreteInfoList.stream().forEach(hsmwConcreteInfo -> {
                        HsmwConcreteOperate operate = new HsmwConcreteOperate();
                        operate.setOrderId(htnOrderInfoVO.getOrderId());
                        operate.setConcreteNum(hsmwConcreteInfo.getConcreteNum());
                        operate.setExpectVolume(hsmwConcreteInfo.getExpectVolume());
                        operate.setSlump(hsmwConcreteInfo.getSlump());
                        operate.setIncreaseandOrDecrease(hsmwConcreteInfo.getIncreaseandOrDecrease());
                       // operate.setOperUser(hsmwUser.getId());
                        hsmwConcreteOperateMapper.insert(operate);
                    });
                    hsmwConcreteOperates = hsmwConcreteOperateMapper.selectList(new LambdaQueryWrapper<HsmwConcreteOperate>()
                            .eq(HsmwConcreteOperate::getOrderId, htnOrderInfoVO.getOrderId()));
                } else {
                    hsmwConcreteOperates = concreteOperates;
                }
                htnOrderInfoVO.setHsmwConcreteOperates(hsmwConcreteOperates);
            });

        }

        return htnOrderInfoVOS;
    }



    /***
     *   UNRECEIVED("1", "等待接单"),
     *     UNSETOUT("2", "等待出发"),
     *     SETOUT("3", "已出发"),
     *     ARRIVED("4","已到达"),
     *     WORKING("5","工作中"),
     *     COMPLETED("6","已完成"),
     *     CANCELED("7","已取消"),
     *     ALL("all","全部");
     * */
    public OrderQueryResultVO getHsmwOrderPageByStatus(BasePage page) {
        HashMap param = new HashMap();
        if (StringUtils.isNotBlank(page.getQueryParam())) {
            param.put("queryParam", page.getQueryParam());
        }
        if (StringUtils.isNotBlank(page.getOrderId())) {
            param.put("orderId", page.getOrderId());
        }
        if (StringUtils.isNotBlank(page.getUserId())) {
            param.put("userId", page.getUserId());
        }
        if (StringUtils.isNotBlank(page.getItemId())) {
            param.put("itemId", page.getItemId());
        }
        if ("1".equals(page.getOrderStatus())) {
            param.put("requestStatus", DistributeStatusEnum.UNRELEASE.getValue());
        } else {
            param.put("orderStatus", page.getOrderStatus());
        }
        if ("7".equals(page.getOrderStatus())) {
            param.put("orderStatus", "6");
            param.put("driverVolumeStatus", "1");
        }
        if ("6".equals(page.getOrderStatus())) {
            param.put("orderStatus", "6");
            param.put("driverVolumeStatus", "0");
        }
        if ("8".equals(page.getOrderStatus())) {
            param.put("orderStatus", page.getOrderStatus());
        }
        OrderQueryResultVO vo = new OrderQueryResultVO();

        if (ChildOrderStatusEnum.CANCELED.getValue().equals(page.getOrderStatus())) {
            OrderTotalInfoVO orderTotalInfoVO = hsmwOrderMapper.getCanceledOrderCountByStatus(param);
            param.put("pageStart", (page.getPageNo() - 1) * page.getPageSize());
            param.put("pageSize", page.getPageSize());
            List<BizOrderDTO> orderList = hsmwOrderMapper.getConceledOrderPageByStatus(param);
            if (ChildOrderStatusEnum.STARTUP.getValue().equals(page.getOrderStatus()) || ChildOrderStatusEnum.ARRIVED.getValue().equals(page.getOrderStatus())) {
                orderList.stream().forEach(order -> {
                    HashMap params = new HashMap();
                    String vehicleLocalteInfo = null;
                    HsmwVehicle vehicle = hsmwVehicleService.getById(order.getVehicleId());
                    if(StringUtils.isNotBlank(vehicle.getImeiNum()) || StringUtils.isNotBlank(vehicle.getIdentifyingCode())){
                        GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(vehicle.getImeiNum(),vehicle.getFlag(),vehicle.getIdentifyingCode());
                        if (StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
                            vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                        }
                    }
                    order.setVehicleLocation(vehicleLocalteInfo);
                    if (ChildOrderStatusEnum.ARRIVED.getValue().equals(page.getOrderStatus())) {
                        List<HsmwForcemanAddress> addresses = hsmwForcemanAddressService.list(new LambdaQueryWrapper<HsmwForcemanAddress>()
                                .eq(HsmwForcemanAddress::getItemId, order.getItemId())
                                .orderByDesc(HsmwForcemanAddress::getCreateTime));
                        order.setAddresses(addresses);
                    }
                });
            }
            vo.setOrderTotalInfoVO(orderTotalInfoVO);
            vo.setOrderList(orderList);
        } else if(ChildOrderStatusEnum.COMPLETED.getValue().equals(page.getOrderStatus()) || ChildOrderStatusEnum.UNDERREVIEW.getValue().equals(page.getOrderStatus())){
            OrderTotalInfoVO orderTotalInfoVO = hsmwOrderMapper.getCompleteOrderCountByStatus(param);
            param.put("pageStart", (page.getPageNo() - 1) * page.getPageSize());
            param.put("pageSize", page.getPageSize());
            List<BizOrderDTO> orderList = hsmwOrderMapper.getCompleteOrderPageByStatus(param);
            if (ChildOrderStatusEnum.STARTUP.getValue().equals(page.getOrderStatus()) || ChildOrderStatusEnum.ARRIVED.getValue().equals(page.getOrderStatus())) {
                orderList.stream().forEach(order -> {
                    HashMap params = new HashMap();
                    String vehicleLocalteInfo = null;
                    HsmwVehicle vehicle = hsmwVehicleService.getById(order.getVehicleId());
                    if(StringUtils.isNotBlank(vehicle.getImeiNum()) || StringUtils.isNotBlank(vehicle.getIdentifyingCode())){
                        GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(vehicle.getImeiNum(),vehicle.getFlag(),vehicle.getIdentifyingCode());
                        if (StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
                            vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                        }
                    }
                    order.setVehicleLocation(vehicleLocalteInfo);
                    if (ChildOrderStatusEnum.ARRIVED.getValue().equals(page.getOrderStatus())) {
                        List<HsmwForcemanAddress> addresses = hsmwForcemanAddressService.list(new LambdaQueryWrapper<HsmwForcemanAddress>()
                                .eq(HsmwForcemanAddress::getItemId, order.getItemId())
                                .orderByDesc(HsmwForcemanAddress::getCreateTime));
                        order.setAddresses(addresses);
                    }
                });
            }
            vo.setOrderTotalInfoVO(orderTotalInfoVO);
            vo.setOrderList(orderList);


        }else {
            OrderTotalInfoVO orderTotalInfoVO = hsmwOrderMapper.getHsmwOrderCountByStatus(param);
            param.put("pageStart", (page.getPageNo() - 1) * page.getPageSize());
            param.put("pageSize", page.getPageSize());
            List<BizOrderDTO> orderList = hsmwOrderMapper.getHsmwOrderPageByStatus(param);
            if (ChildOrderStatusEnum.STARTUP.getValue().equals(page.getOrderStatus()) || ChildOrderStatusEnum.ARRIVED.getValue().equals(page.getOrderStatus())) {
                orderList.stream().forEach(order -> {
                    HashMap params = new HashMap();
                    String vehicleLocalteInfo = null;
                    HsmwVehicle vehicle = hsmwVehicleService.getById(order.getVehicleId());
                    if(StringUtils.isNotBlank(vehicle.getImeiNum()) || StringUtils.isNotBlank(vehicle.getIdentifyingCode())){
                        GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(vehicle.getImeiNum(),vehicle.getFlag(),vehicle.getIdentifyingCode());
                        if (StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
                            vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                        }
                    }
                    order.setVehicleLocation(vehicleLocalteInfo);
                    if (ChildOrderStatusEnum.ARRIVED.getValue().equals(page.getOrderStatus())) {
                        List<HsmwForcemanAddress> addresses = hsmwForcemanAddressService.list(new LambdaQueryWrapper<HsmwForcemanAddress>()
                                .eq(HsmwForcemanAddress::getItemId, order.getItemId())
                                .orderByDesc(HsmwForcemanAddress::getCreateTime));
                        order.setAddresses(addresses);
                    }
                });
            }
            vo.setOrderTotalInfoVO(orderTotalInfoVO);
            vo.setOrderList(orderList);


        }


        return vo;
    }

    public OrderQueryResultVO getHsmwOrderPageByParam(String orderId) {
        HashMap param = new HashMap();
        if (StringUtils.isNotBlank(orderId)) {
            param.put("orderId", orderId);
        }
        OrderQueryResultVO vo = new OrderQueryResultVO();
        List<BizOrderDTO> orderList = hsmwOrderMapper.getHsmwOrderPageByParam(param);
        orderList.stream().forEach(order -> {
            if (ChildOrderStatusEnum.STARTUP.getValue().equals(order.getOrderStatus()) || ChildOrderStatusEnum.ARRIVED.getValue().equals(order.getOrderStatus())) {
                HashMap params = new HashMap();
                String vehicleLocalteInfo = null;
                HsmwVehicle vehicle = hsmwVehicleService.getById(order.getVehicleId());
                if(StringUtils.isNotBlank(vehicle.getImeiNum()) || StringUtils.isNotBlank(vehicle.getIdentifyingCode())){
                    GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(vehicle.getImeiNum(),vehicle.getFlag(),vehicle.getIdentifyingCode());
                    if (StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
                        vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                    }
                }
                order.setVehicleLocation(vehicleLocalteInfo);
                if (ChildOrderStatusEnum.ARRIVED.getValue().equals(order.getOrderStatus())) {
                    List<HsmwForcemanAddress> addresses = hsmwForcemanAddressService.list(new LambdaQueryWrapper<HsmwForcemanAddress>()
                            .eq(HsmwForcemanAddress::getItemId, order.getItemId())
                            .orderByDesc(HsmwForcemanAddress::getCreateTime));
                    order.setAddresses(addresses);
                }
            }
        });
        vo.setOrderList(orderList);
        return vo;
    }


    /***
     *   UNRECEIVED("1", "等待接单"),
     *     UNSETOUT("2", "等待出发"),
     *     SETOUT("3", "已出发"),
     *     ARRIVED("4","已到达"),
     *     WORKING("5","工作中"),
     *     COMPLETED("6","已完成"),
     *     CANCELED("7","已取消"),
     *     ALL("all","全部");
     * */
    public HashMap getTotalByStatus(BasePage page) {
        HashMap param = new HashMap();
        if (StringUtils.isNotBlank(page.getQueryParam())) {
            param.put("queryParam", page.getQueryParam());
        }
        if (StringUtils.isNotBlank(page.getUserId())) {
            param.put("userId", page.getUserId());
        }
        if (StringUtils.isNotBlank(page.getItemId())) {
            param.put("itemId", page.getItemId());
        }
        if ("1".equals(page.getOrderStatus())) {
            param.put("requestStatus", DistributeStatusEnum.UNRELEASE.getValue());
        } else {
            param.put("orderStatus", page.getOrderStatus());
        }
        HashMap result = new HashMap();
        List<BizOrderDTO> allOrderList = hsmwOrderMapper.getHsmwOrderPageByStatus(param);
        long orderCount = 0;
        double volumeSum = 0.0;
        if (CollectionUtil.isNotEmpty(allOrderList)) {
            orderCount = allOrderList.size();
            for (BizOrderDTO order : allOrderList) {
                volumeSum += Double.parseDouble(order.getExpectVolume());
            }
        }
        result.put("orderCount", orderCount);
        result.put("volumeSum", volumeSum);
        return result;
    }


    //查询泵车的订单列表
    public HashMap getConcreteOrderList(BasePage page) {
        HashMap param = new HashMap();
        HashMap result = new HashMap();
        param.put("orderId", page.getOrderId());
        List<BizOrderDTO> orderList = hsmwOrderMapper.getHsmwOrderPageByStatus(param);
        if (ChildOrderStatusEnum.STARTUP.getValue().equals(page.getOrderStatus()) || ChildOrderStatusEnum.ARRIVED.getValue().equals(page.getOrderStatus())) {
            orderList.stream().forEach(order -> {
                HashMap params = new HashMap();
                String vehicleLocalteInfo = null;
                HsmwVehicle vehicle = hsmwVehicleService.getById(order.getVehicleId());
                if(StringUtils.isNotBlank(vehicle.getImeiNum()) || StringUtils.isNotBlank(vehicle.getIdentifyingCode())){
                    GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(vehicle.getImeiNum(),vehicle.getFlag(),vehicle.getIdentifyingCode());
                    if (StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
                        vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                    }
                }
                order.setVehicleLocation(vehicleLocalteInfo);
            });
        }
        result.put("orderList", orderList);
        List<HsmwConcreteOperateRecord> records = hsmwConcreteOperateRecordService.list(new LambdaQueryWrapper<HsmwConcreteOperateRecord>()
                .eq(HsmwConcreteOperateRecord::getOrderId, page.getOrderId()).orderByDesc(HsmwConcreteOperateRecord::getCreateTime));
        result.put("records", records);
        HashMap params = new HashMap();
        params.put("orderId", page.getOrderId());
        List<HsmwConstructionPosition> constructionPositions = hsmwConstructionPositionService.selectConstructionList(params);
        result.put("constructionPositions", constructionPositions);
        HsmwOrder order = hsmwOrderMapper.selectById(page.getOrderId());
        result.put("plantName", order.getConcretePlantName());
        result.put("orderStatus", order.getOrderStatus());
        return result;
    }

    public IPage<OutLeasingOrderVO> getOutLeasingOrderList(BasePage page) {
        HashMap param = new HashMap();
        if (StringUtils.isNotBlank(page.getQueryParam())) {
            param.put("queryParam", page.getQueryParam());
        }
        if (StringUtils.isNotBlank(page.getOrderStatus())) {
            param.put("orderStatus", page.getOrderStatus());
        }
        HashMap result = new HashMap();
        List<OutLeasingOrderVO> allOrderList = hsmwOrderMapper.getOutLeasingOrderList(param);
        param.put("pageStart", (page.getPageNo() - 1) * page.getPageSize());
        param.put("pageSize", page.getPageSize());
        List<OutLeasingOrderVO> orderList = hsmwOrderMapper.getOutLeasingOrderList(param);
        IPage<OutLeasingOrderVO> orderPage = new Page<>();
        orderPage.setTotal(allOrderList.size());
        orderPage.setCurrent(page.getPageNo());
        orderPage.setRecords(orderList);
        orderPage.setSize(page.getPageSize());
        long total = allOrderList.size();
        long pages = 0;
        pages = total / page.getPageSize();
        if (total % page.getPageSize() != 0) {
            pages = pages + 1;
        }
        orderPage.setPages(pages);

        result.put("data", orderPage);
        return orderPage;
    }


    public Object foreManFindOrderStatusList(String param, String id) {
        if (OrderStatusEnum.UNRECEIVED.getValue().equals(param)) {
            param = "0,1";
        }
        List<IdleVehicleVo> idleVehicleVos = hsmwOrderMapper.foreManFindOrderStatusList(param, id);
        for (IdleVehicleVo hsmwOrder : idleVehicleVos) {
            String orderId = hsmwOrder.getOrderId();
            List<PositionAndVehicleVo> list = hsmwConstructionPositionService.findPositionAndvehicleList(orderId);
            hsmwOrder.setPositionAndVehicleVos(list);
        }
        return idleVehicleVos;
    }


    public IdleVehicleVo findOrderDetailsByOrderId(String orderId) {
        LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();

        IdleVehicleVo hsmwOrder = hsmwOrderMapper.findOrderDetailsByOrderId(orderId);

        String concretePlantId = hsmwOrder.getConcretePlantId();
        HsmwConcretePlantInfo hsmwConcretePlantInfo = hsmwConcretePlantInfoMapper.selectById(concretePlantId);
        if (hsmwConcretePlantInfo != null) {
            HsmwConcreteUser user = hsmwConcreteUserMapper.selectById(hsmwConcretePlantInfo.getUserId());
            hsmwOrder.setConcretePlantPhone(user.getUsername());
        }

        // 泵车单
        if (StringUtils.isNotBlank(hsmwOrder.getIfTruckRequired()) && StringUtils.equals(CommonConstants.YES, hsmwOrder.getIfTruckRequired())) {

            //通过订单id查询需求车辆信息
            List<RequestVo> requestVos = hsmwOrderVehicleRequestService.findRequstListByOrderId(orderId);
            for (RequestVo requestVo : requestVos) {
                List<PositionAndDriverVo> positions = new ArrayList<>();
                HsmwConstructionPosition positionServiceById = hsmwConstructionPositionService.getById(requestVo.getPositionId());
                PositionAndDriverVo position = new PositionAndDriverVo();
                position.setPosition(positionServiceById.getPosition());
                String requestId = requestVo.getReId();
                HsmwOrderVehicleRelation re = hsmwOrderVehicleRelationService.getOne(new LambdaQueryWrapper<HsmwOrderVehicleRelation>().eq(HsmwOrderVehicleRelation::getOrderVehicleRequestId, requestId).ne(HsmwOrderVehicleRelation::getOrderStatus,ChildOrderStatusEnum.CANCELED.getValue()));
                if (re != null) {
                    position.setVehicleId(re.getVehicleId());
                    position.setRelationId(re.getId());
                    position.setVehicleNum(re.getVehicleNum());
                    position.setOrderStatus(re.getOrderStatus());
                    requestVo.setOutsideLeasingFlag(re.getOutsideLeasingFlag());
                    String itemId = hsmwOrder.getItemId();
                    HsmwItem hsmwItem = hsmwItemService.getById(itemId);
                    String vehicleLocalteInfo = null;
                    String destinationLocateInfo = hsmwItem.getLng() + "," + hsmwItem.getLat();
                    String vehicleId = re.getVehicleId();

                    String outsideLeasingFlag = re.getOutsideLeasingFlag();
                    //判断是不是外租泵车
                    if(outsideLeasingFlag.equals("1")){
                        List<DriverDetailVO> driverDetailVOS = new ArrayList<>();
                        DriverDetailVO driverDetailVO = new DriverDetailVO();
                        driverDetailVO.setName(re.getDriverName());
                        driverDetailVO.setUsername(re.getDriverUsername());
                        driverDetailVOS.add(driverDetailVO);
                        position.setDriverDetailInfoVOS(driverDetailVOS);
                    }
                    if (StringUtils.isNotBlank(vehicleId)) {

                        // 不是外租泵车的话 根据车辆id 或者relationId 查询司机信息
                        if (!re.getOrderStatus().equals(ChildOrderStatusEnum.COMPLETED.getValue())) {
                            List<DriverDetailVO> driverDetailVOS = hsmwUserDriverService.findDriverListById(vehicleId);
                            for (DriverDetailVO driverDetailVO : driverDetailVOS) {
                                String driId = driverDetailVO.getDriverId();
                                HsmwForcemanEvaluate forcemanEvaluate = hsmwForcemanEvaluateService.getOne(new LambdaQueryWrapper<HsmwForcemanEvaluate>().eq(HsmwForcemanEvaluate::getDriverId, driId).eq(HsmwForcemanEvaluate::getRelationId, re.getId()));
                                driverDetailVO.setHsmwForcemanEvaluate(forcemanEvaluate);
                            }
                            position.setDriverDetailInfoVOS(driverDetailVOS);
                        } else {

                            List<DriverDetailVO> driverDetailVOS = hsmwUserDriverService.findDriverListByRelatId(re.getId());
                            for (DriverDetailVO driverDetailVO : driverDetailVOS) {
                                String driId = driverDetailVO.getDriverId();
                                HsmwForcemanEvaluate forcemanEvaluate = hsmwForcemanEvaluateService.getOne(new LambdaQueryWrapper<HsmwForcemanEvaluate>().eq(HsmwForcemanEvaluate::getDriverId, driId).eq(HsmwForcemanEvaluate::getRelationId, re.getId()));
                                driverDetailVO.setHsmwForcemanEvaluate(forcemanEvaluate);
                            }
                            position.setDriverDetailInfoVOS(driverDetailVOS);
                        }

                        HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(vehicleId);
                        if (StringUtils.isNotBlank(hsmwVehicle.getImeiNum()) || StringUtils.isNotBlank(hsmwVehicle.getIdentifyingCode())) {
                            GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(hsmwVehicle.getImeiNum(),hsmwVehicle.getFlag(),hsmwVehicle.getIdentifyingCode());
                            if (StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
                                vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                            }
                        }
                        HashMap calculateParam = new HashMap();
                        calculateParam.put("origin", vehicleLocalteInfo);
                        calculateParam.put("destination", destinationLocateInfo);
                        Long mapTimeAndDistance = GaoDeInfoUtils.calculateDistance(calculateParam);
                        long distence = mapTimeAndDistance / 1000;
                        requestVo.setDistance(distence);

                        HsmwReport hsmwReport = hsmwReportMapper.selectOne(new LambdaQueryWrapper<HsmwReport>().in(HsmwReport::getReportType, 2, 3, 4).in(HsmwReport::getExamineType, 0, 1).eq(HsmwReport::getVehicleId, vehicleId).last("LIMIT 1"));
                        if (hsmwReport != null) {
                            requestVo.setReportType(hsmwReport.getReportType());
                        }
                    }
                    requestVo.setDestinationLocateInfo(destinationLocateInfo);
                    requestVo.setVehicleLocalteInfo(vehicleLocalteInfo);
                    requestVo.setNewVehicleFlag(re.getNewVehicleFlag());
                }
                positions.add(position);
                requestVo.setPositionAndDriverVos(positions);
            }
            hsmwOrder.setPositionAndDriverVos(requestVos);
        }
        HashMap param = new HashMap();
        param.put("orderId", orderId);
        //查询有混凝土记录那么 直接查询如果 没有记录 就查询记录并 查询出来
        List<HsmwConcreteOperate> hsmwConcreteOperates = null;
        List<HsmwConcreteOperate> concreteOperates = hsmwConcreteOperateService.list(new LambdaQueryWrapper<HsmwConcreteOperate>()
                .eq(HsmwConcreteOperate::getOrderId, orderId));
        if (CollectionUtil.isEmpty(concreteOperates)) {
            //查询出全部的混凝土的标号的类型
            List<HsmwConcreteInfo> hsmwConcreteInfoList = hsmwConcreteInfoMapper.selectConcretelist(param);
            hsmwConcreteInfoList.stream().forEach(hsmwConcreteInfo -> {
                HsmwConcreteOperate operate = new HsmwConcreteOperate();
                operate.setOrderId(orderId);
                operate.setConcreteNum(hsmwConcreteInfo.getConcreteNum());
                operate.setExpectVolume(hsmwConcreteInfo.getExpectVolume());
                operate.setSlump(hsmwConcreteInfo.getSlump());
                operate.setIncreaseandOrDecrease(hsmwConcreteInfo.getIncreaseandOrDecrease());
                operate.setOperUser(hsmwUser.getId());
                hsmwConcreteOperateMapper.insert(operate);
            });
            hsmwConcreteOperates = hsmwConcreteOperateMapper.selectList(new LambdaQueryWrapper<HsmwConcreteOperate>()
                    .eq(HsmwConcreteOperate::getOrderId, orderId));
        } else {
            hsmwConcreteOperates = concreteOperates;
        }
        HashMap params = new HashMap();
        params.put("orderId", orderId);
        List<HsmwConstructionPosition> constructionPositions = hsmwConstructionPositionService.selectConstructionList(params);
        hsmwOrder.setHsmwConcreteOperates(hsmwConcreteOperates);
        hsmwOrder.setHsmwConstructionPositionList(constructionPositions);

        //计算实时方量的汇总
        List<HsmwOrderVehicleRelation> relations = hsmwOrderVehicleRelationService.list(new LambdaQueryWrapper<HsmwOrderVehicleRelation>()
                .eq(HsmwOrderVehicleRelation::getOrderId, orderId));
        Double realVolumeSum = 0.00;
        if (CollectionUtil.isNotEmpty(relations)) {
            for (HsmwOrderVehicleRelation rela : relations) {
                if (StringUtils.isNotBlank(rela.getRealTimeVolume())) {
                    realVolumeSum += Double.parseDouble(rela.getRealTimeVolume());
                }
            }
        }

        hsmwOrder.setRealTimeVolume(realVolumeSum);
        return hsmwOrder;
    }

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
    }

    public List<RetailerAdressInfoVO> getRetailerRecentAdress(String userId) {
        return hsmwOrderMapper.getRetailerRecentAdress(userId);
    }

    public HashMap getHsmwOrderDetailByOrderId(String orderId) {
        HashMap param = new HashMap();
        if (StringUtils.isNotBlank(orderId)) {
            param.put("orderId", orderId);
        }
        HsmwOrder orderInfo = hsmwOrderService.getHsmwOrderById(orderId);
        HashMap result = new HashMap();
        List<BizOrderDTO> allOrderList = hsmwOrderMapper.getHsmwOrderPageByStatus(param);
        List<BizOrderDTO> goingList = new ArrayList<>();
        //遍历 并将进行中的放在新的list中
        Iterator<BizOrderDTO> iterator = allOrderList.iterator();
        while (iterator.hasNext()) {
            BizOrderDTO orderDTO = iterator.next();
            if (ChildOrderStatusEnum.ARRIVED.getValue().equals(orderDTO.getOrderStatus())) {
                goingList.add(orderDTO);
                iterator.remove();//使用迭代器的删除方法删除
            }
        }
        allOrderList.stream().forEach(order -> {
            if (ChildOrderStatusEnum.STARTUP.getValue().equals(order.getOrderStatus()) || ChildOrderStatusEnum.ARRIVED.getValue().equals(order.getOrderStatus())) {
                HashMap params = new HashMap();
                String vehicleLocalteInfo = null;

                HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(order.getVehicleId());
                if (StringUtils.isNotBlank(hsmwVehicle.getImeiNum()) || StringUtils.isNotBlank(hsmwVehicle.getIdentifyingCode())) {
                    GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(hsmwVehicle.getImeiNum(),hsmwVehicle.getFlag(),hsmwVehicle.getIdentifyingCode());
                    if (StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
                        vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                    }
                }
                order.setVehicleLocation(vehicleLocalteInfo);
            }
        });
        HashMap params = new HashMap();
        params.put("orderId", orderId);
        List<HsmwConstructionPosition> constructionPositions = hsmwConstructionPositionService.selectConstructionList(params);
        result.put("constructionPositions", constructionPositions);
        List<HsmwConcreteOperateRecord> records = hsmwConcreteOperateRecordService.list(new LambdaQueryWrapper<HsmwConcreteOperateRecord>()
                .eq(HsmwConcreteOperateRecord::getOrderId, orderId)
                .orderByDesc(HsmwConcreteOperateRecord::getCreateTime));
        List<HsmwConcreteOperate> operates = hsmwConcreteOperateService.list(new LambdaQueryWrapper<HsmwConcreteOperate>()
                .eq(HsmwConcreteOperate::getOrderId, orderId));
        result.put("records", records);
        result.put("operates", operates);
        result.put("orderList", allOrderList);
        result.put("goingList", goingList);
        result.put("plantName", orderInfo.getConcretePlantName());
        result.put("itemName", orderInfo.getItemName());
        result.put("orderStatus", orderInfo.getOrderStatus());
        return result;
    }

    public IdleVehicleVo getOrderDetail(String orderId) {
        IdleVehicleVo idleVehicleVos = hsmwOrderMapper.findOrderinfoByOrderId(orderId);
        List<HsmwVolumeRecord> recordes = hsmwVolumeRecordService.list(new LambdaQueryWrapper<HsmwVolumeRecord>()
                .eq(HsmwVolumeRecord::getRelationId, idleVehicleVos.getRelationId()));
        idleVehicleVos.setRecordes(recordes);
        return idleVehicleVos;
    }

    public DataResponse addOutLeasingPump(OutLeasingOrderVO orderVO) {
        try {
            LoginUser user = currentHsmwUserUtils.getCurrentUserInfo();
            HsmwOrderVehicleRelation relation = new HsmwOrderVehicleRelation();
            relation.setOrderId(orderVO.getOrderId());
            relation.setVehicleNum(orderVO.getVehicleNum());
            relation.setVehicleModel(orderVO.getVehicleModel());
            relation.setVehicleModel(orderVO.getVehicleModel());
            relation.setAcceptOrderTime(LocalDateTime.now());
            relation.setOutsideLeasingFlag(CommonConstants.YES);
            relation.setOrderVehicleRequestId(orderVO.getRequestId());
            relation.setCreateUser(user.getId());
            relation.setDriverName(orderVO.getDriverName());
            relation.setDriverUsername(orderVO.getDriverUsername());
            relation.setOrderStatus(ChildOrderStatusEnum.RECEIVED.getValue());
            hsmwOrderVehicleRelationService.save(relation);
            HsmwOrderVehicleRequest request = hsmwOrderVehicleRequestMapper.selectById(orderVO.getRequestId());
            request.setRequestStatus(RequestStatusEnum.RECEIVED.getValue());
            request.setVersion(request.getVersion()+1);
            hsmwOrderVehicleRequestService.updateById(request);
            return  new DataResponse();
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"确认方量失败，请联系管理员！");
        }
    }

    public List<HsmwOrder> expireConcreteOrders() {
        return hsmwOrderMapper.expireConcreteOrders();
    }

    public Double selectItemInfoByItemId(HashMap param) {
        return hsmwOrderMapper.selectItemInfoByItemId(param);
    }

    public void saveOrderVo(BeanUtilsOrderVO beanUtilsOrderVO) {

        hsmwOrderMapper.saveOrderVo(beanUtilsOrderVO);
    }

    public HtnPumpOrderDetailVo  selectOrderDetailByRelationId(HashMap param) {
        HtnPumpOrderDetailVo vo = hsmwOrderMapper.selectOrderDetailByRelationId(param);
        String vehicleId = vo.getVehicleId();
        String orderId = vo.getOrderId();
        HashMap params = new HashMap();
        params.put("orderId",orderId);
        if(StringUtils.isNotBlank(vehicleId)){
            if(StringUtils.isNotNull(vo.getCollectFlag()) && vo.getCollectFlag()>0){
                vo.setCollectFlag(1);
            }else {
                vo.setCollectFlag(0);
            }
            param.put("vehicleId",vehicleId);
            HashMap paramss  = new HashMap();
            paramss.put("relationId",vo.getRelationId());
            List<DriverCountVO> driverCountVOS =new ArrayList<>();
            if(ChildOrderStatusEnum.RECEIVED.getValue().equals(vo.getOrderStatus())
                    ||ChildOrderStatusEnum.STARTUP.getValue().equals(vo.getOrderStatus())
                    || ChildOrderStatusEnum.ARRIVED.getValue().equals(vo.getOrderStatus())){
                    driverCountVOS=hsmwOrderMapper.findUserDriverListBYVehicleId(vehicleId);
            }
            if(ChildOrderStatusEnum.WORKING.getValue().equals(vo.getOrderStatus())
                    || ChildOrderStatusEnum.COMPLETED.getValue().equals(vo.getOrderStatus())
                    || ChildOrderStatusEnum.CANCELED.getValue().equals(vo.getOrderStatus())
                    || ChildOrderStatusEnum.UNDERREVIEW.getValue().equals(vo.getOrderStatus())){
               driverCountVOS = hsmwOrderMapper.findDriverRecordByParam(paramss);
            }
            if(CollectionUtil.isEmpty(driverCountVOS)){
                driverCountVOS=hsmwOrderMapper.findUserDriverListByParam(paramss);
            }
            if(CollectionUtil.isNotEmpty(driverCountVOS)){
                driverCountVOS.stream().forEach(driverCountVO -> {
                    HsmwForcemanEvaluate forcemanEvaluate = hsmwForcemanEvaluateService.getOne(new LambdaQueryWrapper<HsmwForcemanEvaluate>().eq(HsmwForcemanEvaluate::getDriverId, driverCountVO.getDriverId()).eq(HsmwForcemanEvaluate::getRelationId,vo.getRelationId()));
                    driverCountVO.setHsmwForcemanEvaluate(forcemanEvaluate);
                });
            }
            vo.setDriverCountVOS(driverCountVOS);
            Integer count = hsmwOrderMapper.selectAvaliableCount(params);
            vo.setAvaliableCount(count);
            if(OrderTypeEnum.CONCRETE_ORDER.getValue().equals(vo.getOrderType())){
                //查询有混凝土记录那么 直接查询如果 没有记录 就查询记录并 查询出来
                List<HsmwConcreteOperate> hsmwConcreteOperates = null;
                List<HsmwConcreteOperate> concreteOperates = hsmwConcreteOperateService.list(new LambdaQueryWrapper<HsmwConcreteOperate>()
                        .eq(HsmwConcreteOperate::getOrderId, vo.getOrderId()));
                if (CollectionUtil.isEmpty(concreteOperates)) {
                    //查询出全部的混凝土的标号的类型
                    List<HsmwConcreteInfo> hsmwConcreteInfoList = hsmwConcreteInfoMapper.selectConcretelist(params);
                    hsmwConcreteInfoList.stream().forEach(hsmwConcreteInfo -> {
                        HsmwConcreteOperate operate = new HsmwConcreteOperate();
                        operate.setOrderId(vo.getOrderId());
                        operate.setConcreteNum(hsmwConcreteInfo.getConcreteNum());
                        operate.setExpectVolume(hsmwConcreteInfo.getExpectVolume());
                        operate.setSlump(hsmwConcreteInfo.getSlump());
                        operate.setIncreaseandOrDecrease(hsmwConcreteInfo.getIncreaseandOrDecrease());

                        // operate.setOperUser(hsmwUser.getId());
                        hsmwConcreteOperateMapper.insert(operate);
                    });
                    hsmwConcreteOperates = hsmwConcreteOperateMapper.selectList(new LambdaQueryWrapper<HsmwConcreteOperate>()
                            .eq(HsmwConcreteOperate::getOrderId, vo.getOrderId()));
                } else {
                    hsmwConcreteOperates = concreteOperates;
                }
                vo.setHsmwConcreteOperates(hsmwConcreteOperates);
            }
            HashMap paramInfo = new HashMap();
            HsmwHtnUser currentHtnHsmwUser  =currentHsmwUserUtils.getCurrentHtnUserInfo();
            if(StringUtils.isNotBlank(currentHtnHsmwUser.getType())
                    && (HtnUserTypeEnum.CONCRETE.getValue().equals(currentHtnHsmwUser.getType())
                    ||HtnUserTypeEnum.COMPANY.getValue().equals(currentHtnHsmwUser.getType()))){
                paramInfo.put("companyId",currentHtnHsmwUser.getOwnCompanyId());
            }else {
                paramInfo.put("userId",currentHtnHsmwUser.getId());
            }
            paramInfo.put("vehicleId",vehicleId);
            Integer counts =hsmwOrderMapper.selectSelectFlag(paramInfo);
            if(null!= counts  && counts>0){
                vo.setCollectFlag(1);
            }else {
                vo.setCollectFlag(0);
            }

        }

        // 查询调度备注信息
        List<HsmwDispatchOrderRemark> dispatchOrderRemarks = hsmwDispatchOrderRemarkMapper.selectList(new LambdaQueryWrapper<HsmwDispatchOrderRemark>()
                .eq(HsmwDispatchOrderRemark::getRequestId,vo.getRequestId()));
        vo.setDispatchOrderRemarks(dispatchOrderRemarks);

        List<HsmwConstructionPosition > ps= hsmwOrderMapper.selectPositionsByOrderId(params);
        vo.setHsmwConstructionPositionList(ps);
        return vo;
    }

    double[] getYearBetween(String  value){
        if(value.equals(VehicleYearsEnum.YEAR_0_3.getValue())){
            String name = VehicleYearsEnum.YEAR_0_3.getName();
            String[] names = name.split(",");
            return  new double[]{Double.valueOf(names[0]),Double.valueOf(names[1])};
        }
        if(value.equals(VehicleYearsEnum.YEAR_3_5.getValue())){
            String name = VehicleYearsEnum.YEAR_3_5.getName();
            String[] names = name.split(",");
            return  new double[]{Double.valueOf(names[0]),Double.valueOf(names[1])};
        }
        if(value.equals(VehicleYearsEnum.YEAR_5_7.getValue())){
            String name = VehicleYearsEnum.YEAR_5_7.getName();
            String[] names = name.split(",");
            return  new double[]{Double.valueOf(names[0]),Double.valueOf(names[1])};
        }
        if(value.equals(VehicleYearsEnum.YEAR_7_10.getValue())){
            String name = VehicleYearsEnum.YEAR_7_10.getName();
            String[] names = name.split(",");
            return  new double[]{Double.valueOf(names[0]),Double.valueOf(names[1])};
        }
        return  new double[]{10,15};

    }


    public DataResponse updateOrderInfo(OrderUpdateVO orderUpdateVO) {
        LoginUser loginUser =currentHsmwUserUtils.getCurrentUserInfo();
        //如果到达时间不为空，那么就是修改到达时间
        if(StringUtils.isNotNull(orderUpdateVO.getReachTime())){
            if (StringUtils.isBlank(orderUpdateVO.getRequestId())){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的需求Id不能为空");
            }
            if (StringUtils.isBlank(orderUpdateVO.getRequestStatus())){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的需求状态不能为空");
            }
            boolean flag=false;
            HsmwOrderVehicleRequest request = hsmwOrderVehicleRequestMapper.selectById(orderUpdateVO.getRequestId());
            if(StringUtils.isNotNull(request)){
                if(!request.getRequestStatus().equals(orderUpdateVO.getRequestStatus())){
                    return new DataResponse(CommonConstants.ResponseStatus.ORDER_STATUS_CHANGED,"");
                }else {
                    flag=true;
                }
            }
            if(StringUtils.isNotBlank(orderUpdateVO.getOrderStatus())){
                HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationMapper.selectById(orderUpdateVO.getRelationId());
                if(StringUtils.isNotNull(relation)){
                    if(!relation.getOrderStatus().equals(orderUpdateVO.getOrderStatus())){
                        return new DataResponse(CommonConstants.ResponseStatus.ORDER_STATUS_CHANGED,"");
                    }else {
                        flag=true;
                    }
                    HashMap param  = new HashMap();
                    param.put("vehicleId",relation.getVehicleId());
                    relation.setUpdateTimeFlag(1);
                    hsmwOrderVehicleRelationMapper.updateById(relation);
                    List<HsmwDriverUser > driverUsers = hsmwDriverUserMapper.selectAvalableUser(param);
                    DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
                    String[] params = new String[]{dtf2.format(orderUpdateVO.getReachTime())};
                    String message = "您的订单预计到达时间已被修改为"+dtf2.format(orderUpdateVO.getReachTime())+"，如有问题请联系施工方并协商，如无法准时到达取消订单将不扣积分";
                    if(CollectionUtil.isNotEmpty(driverUsers)){
                        driverUsers.stream().forEach(driverUser ->{
                            SendSmsUtil.sendSmsWithParam(appId, appKey, params, htnUpdateTime, smsSign, driverUser.getUsername());
                            TencentPushUtils.pushMsg(message,driverUser.getUsername(),"");
                            //新增系统消息
                            HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                            hsmwDriverNews.setUserId(driverUser.getId());
                            hsmwDriverNews.setMessage(message);
                            hsmwDriverNews.setAlreadyRead("0");
                            hsmwDriverNewsService.save(hsmwDriverNews);
                        });
                    }
                }
                hsmwOrderVehicleRelationMapper.updateById(relation);
            }
            if(flag){
                request.setReachTime(orderUpdateVO.getReachTime());
                request.setUpdateTimeFlag(true);
                hsmwOrderVehicleRequestService.updateById(request);
            }
        }
        //如果施工信息
        if(CollectionUtil.isNotEmpty(orderUpdateVO.getHsmwConstructionPositionList())){
            if(!orderUpdateVO.getOrderId().equals(orderUpdateVO.getOrderId())){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的订单Id不能为空");
            }
            HsmwOrder order = hsmwOrderService.getHsmwOrderById(orderUpdateVO.getOrderId());
            //首先删除之前的施工部位信息
            hsmwConstructionPositionService.remove(new LambdaQueryWrapper<HsmwConstructionPosition>()
                    .eq(HsmwConstructionPosition::getOrderId,orderUpdateVO.getOrderId()));
            hsmwConcreteInfoService.removeUnusedConcreteInfo(orderUpdateVO.getOrderId());
            //新增传过来的施工部位信息
            List<HsmwConstructionPosition> positions = orderUpdateVO.getHsmwConstructionPositionList();
            List<HsmwConcreteInfo> hsmwConcreteInfos = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(positions)) {
                AtomicReference<Double> expectVolumeSum = new AtomicReference<>(0.0);
                positions.stream().forEach(hsmwConstructionPosition -> {
                    String positionId = CommonUtils.generateId(hsmwConstructionPosition);
                    hsmwConstructionPosition.setOrderId(orderUpdateVO.getOrderId());
                    hsmwConstructionPosition.setId(positionId);
                    hsmwConstructionPosition.setCreateUser(loginUser.getId());
                    List<HsmwConcreteInfo> hsmwConcreteInfss = hsmwConstructionPosition.getHsmwConcreteInfos();
                    if (CollectionUtil.isNotEmpty(hsmwConcreteInfss)) {
                        hsmwConcreteInfss.stream().forEach(hsmwConcreteInfo -> {
                            hsmwConcreteInfo.setCreateUser(loginUser.getId());
                            hsmwConcreteInfo.setPositionId(positionId);
                            hsmwConcreteInfos.add(hsmwConcreteInfo);
                            expectVolumeSum.updateAndGet(v -> new Double((double) (v + Double.parseDouble(hsmwConcreteInfo.getExpectVolume()))));
                        });
                    }
                });
                order.setExpectVolume(expectVolumeSum.toString());
                hsmwOrderMapper.updateById(order);
                hsmwConcreteInfoService.saveBatch(hsmwConcreteInfos);
                hsmwConstructionPositionService.saveBatch(positions);
            }
        }
       return  new DataResponse(CommonConstants.ResponseStatus.SUCCESS,"操作成功");
    }

    public DataResponse findVehicleCountAndDistance(IdleVehicleQueryVO idleVehicleQueryVO) {
        List<VehicleStatisticsVO> resList = new ArrayList<>();
        HsmwDictType dictType = hsmwDictTypeService.getOne(new LambdaQueryWrapper<HsmwDictType>()
                .eq(HsmwDictType::getDictType,idleVehicleQueryVO.getVehicleType()));
        //根据前端传过来的中文的车辆型号翻译为 数据库中存储的车辆型号
        List<HsmwDictData> vehicleTypes =hsmwDictDataService.list(new LambdaQueryWrapper<HsmwDictData>()
                .eq(HsmwDictData::getDictType,idleVehicleQueryVO.getVehicleType())
                .orderByAsc(HsmwDictData::getDictValue));
        for(HsmwDictData data:vehicleTypes){
            VehicleStatisticsVO vehicleStatisticsVO = new VehicleStatisticsVO();
            Map map = new HashMap();
            List<Long> longList = new ArrayList();
            LambdaQueryWrapper<HsmwVehicle> lambdaQueryWrapper= new LambdaQueryWrapper<HsmwVehicle>();
            lambdaQueryWrapper.eq(HsmwVehicle::getVehicleType, dictType.getDictName());
            lambdaQueryWrapper.eq(HsmwVehicle::getVehicleModel, data.getDictLabel());
            lambdaQueryWrapper.eq(HsmwVehicle::getWorkStatus, CommonConstants.VEHICLE_FREE);
            //如果选择的桥数 不为空 则 在选择车的时候过滤一下。
            if (StringUtils.isNotBlank(idleVehicleQueryVO.getAxis())) {
                List<String> axisList = new ArrayList<>();
                String[] axiss =idleVehicleQueryVO.getAxis().split(",");
                if(axiss.length>0){
                    for(String ax:axiss){
                        axisList.add(ax);
                    }
                }
                lambdaQueryWrapper.in(HsmwVehicle::getAxis, axisList);
            }
            //如果选择的臂节数 不为空 则 在选择车的时候过滤一下。
            if (StringUtils.isNotBlank(idleVehicleQueryVO.getArmSegment())) {
                List<String> segList = new ArrayList<>();
                String[] segss =idleVehicleQueryVO.getArmSegment().split(",");
                if(segss.length>0){
                    for(String ax:segss){
                        segList.add(ax);
                    }
                }
                lambdaQueryWrapper.in(HsmwVehicle::getArmSegment, segList);
            }
            List<HsmwVehicle> list = hsmwVehicleService.list(lambdaQueryWrapper);
            //判断车辆年限
            if(CollectionUtil.isNotEmpty(list) && StringUtils.isNotBlank(idleVehicleQueryVO.getYears()) ){
                Iterator<HsmwVehicle> iterator = list.iterator();
                while (iterator.hasNext()) {
                    HsmwVehicle hsmwVehicle = iterator.next();
                    LocalDate beginDate = hsmwVehicle.getBeginTime();
                    if(StringUtils.isNull(beginDate)){
                        beginDate=LocalDate.now().minusMonths(12);
                    }
                    long year = beginDate.until(LocalDateTime.now(), ChronoUnit.YEARS);
                    long month = beginDate.until(LocalDateTime.now(), ChronoUnit.MONTHS);
                    double yearsValue = month/12.0;
                    String yearStr =idleVehicleQueryVO.getYears();
                    boolean isFitable= false;
                    if(StringUtils.isNotBlank(yearStr)){
                        String[] yearSub = yearStr.split(",");
                        if(yearSub.length>0){
                            for(String str :yearSub){
                                double[] between =  getYearBetween(str);
                                double begin = between[0];
                                double end = between[1];
                                if(yearsValue<=end && yearsValue>begin){
                                    isFitable=true;
                                    break;
                                }
                            }
                        }
                    }
                    if(!isFitable){
                        iterator.remove();
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(list)) {
                for (HsmwVehicle hsmwVehicle : list) {

                    String vehicleLocalteInfo = null;
                    String destinationLocateInfo = idleVehicleQueryVO.getItemLng() + "," + idleVehicleQueryVO.getItemLat();
                    if (StringUtils.isNotBlank(hsmwVehicle.getImeiNum()) || StringUtils.isNotBlank(hsmwVehicle.getIdentifyingCode())) {
                        GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(hsmwVehicle.getImeiNum(),hsmwVehicle.getFlag(),hsmwVehicle.getIdentifyingCode());
                        if (StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
                            vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                        }
                    }
                    HashMap calculateParam = new HashMap();
                    calculateParam.put("origin", vehicleLocalteInfo);
                    calculateParam.put("destination", destinationLocateInfo);
                    Map<String, Long> mapTimeAndDistance = GaoDeInfoUtils.calculateDistanceDistence(calculateParam);
                    Long time =0L;
                    if(StringUtils.isNotNull(mapTimeAndDistance.get("time"))) {
                        time  =mapTimeAndDistance.get("time") / 3600;
                    }
                    vehicleStatisticsVO.setTime(time);
                    vehicleStatisticsVO.setVehicleNum( list.size());
                    Long distence = 0L;
                    if(StringUtils.isNotNull(mapTimeAndDistance.get("distence"))){
                        distence= mapTimeAndDistance.get("distence") / 1000;
                    }
                    System.err.println("距离--->" + distence);
                    longList.add(distence);

                }
                long min = longList.stream().mapToLong(lo -> lo.longValue()).min().orElse(0L);
                vehicleStatisticsVO.setDistance(min);
                vehicleStatisticsVO.setVehicleType(dictType.getDictName());
                vehicleStatisticsVO.setVehicleModel(data.getDictLabel());
                resList.add(vehicleStatisticsVO);
            }else{
                vehicleStatisticsVO.setTime(0);
                vehicleStatisticsVO.setVehicleNum(0);
                vehicleStatisticsVO.setDistance(0);
                vehicleStatisticsVO.setVehicleType(dictType.getDictName());
                vehicleStatisticsVO.setVehicleModel(data.getDictLabel());
                resList.add(vehicleStatisticsVO);
            }
        }
        return new DataResponse<>(CommonConstants.ResponseStatus.SUCCESS, resList);
    }
    //取消 泵车订单
    public DataResponse cancelPumpOrder(OrderCancelVO orderCancelVO) {
        try {
            HsmwHtnUser usernow =currentHsmwUserUtils.getCurrentHtnUserInfo();
            HashMap param = new HashMap();
            param.put("orderId",orderCancelVO.getOrderId());
            List<HsmwOrderVehicleRequest>  requests  = new ArrayList<>();
            if(CommonConstants.YES.equals(orderCancelVO.getType())){
                List<HsmwOrderVehicleRequest> requestList = hsmwOrderVehicleRequestService.selectCancellist(param);
                requests.addAll(requestList);
            }else {
                if(StringUtils.isNotBlank(orderCancelVO.getRequestId())){
                    HsmwOrderVehicleRequest request = hsmwOrderVehicleRequestService.getById(orderCancelVO.getRequestId());
                    requests.add(request);
                }
            }
            //给司机的系统消息
            List<HsmwDriverNews> news =  new ArrayList<>();
            if(CollectionUtil.isNotEmpty(requests)){
                for(HsmwOrderVehicleRequest request:requests ){
                    if(OrderTypeEnum.PUMP_ORDER.getValue().equals(request.getOrderType())){
                        List<HsmwOrderVehicleRelation> relations = hsmwOrderVehicleRelationService.list(new LambdaQueryWrapper<HsmwOrderVehicleRelation>().
                                eq(HsmwOrderVehicleRelation::getOrderVehicleRequestId,request.getId()));
                        if(CollectionUtil.isNotEmpty(relations)){
                            HsmwOrderVehicleRelation relation  = relations.get(0);
                            HsmwPumpOperateRecord record1 = new HsmwPumpOperateRecord();
                            record1.setRequestId(relation.getOrderVehicleRequestId());
                            record1.setOrderId(relation.getOrderId());
                            record1.setCreateTime(LocalDateTime.now());
                            record1.setUsername(usernow.getUsername());
                            record1.setOrderStatus(PumpOrderStatusEnum.CANCLED.getValue());
                            record1.setOperContent("取消订单！");
                            hsmwPumpOperateRecordService.save(record1);
                            String msg ="";
                            if (relation.getOrderStatus().equals(ChildOrderStatusEnum.UNRECEIVED.getValue())
                                    ||  relation.getOrderStatus().equals(ChildOrderStatusEnum.RECEIVED.getValue())
                                    ||  relation.getOrderStatus().equals(ChildOrderStatusEnum.STARTUP.getValue()) ){
                                HsmwOrder order = hsmwOrderService.getById(orderCancelVO.getOrderId());
                                /**
                                 * 先添加 再取消
                                 * 司机已出发取消订单 算作空跑订单
                                 *  新增到空跑记录表里面
                                 *  新增到结算表 hsmworder_blance
                                 */
                                if(StringUtils.equals(relation.getOrderStatus(),ChildOrderStatusEnum.STARTUP.getValue())){

                                    List<HsmwUserDriver> hsmwUserDrivers=  hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>()
                                            .eq(HsmwUserDriver::getVehicleId,relation.getVehicleId())
                                            .eq(HsmwUserDriver::getWorkStatus,CommonConstants.DRIVER_WORK));

                                    //结算记录表
                                    HsmwOrderBalance hsmwOrderBalance = new HsmwOrderBalance();
                                    String userName = "";
                                    List<HsmwRunSprintRecord> hsmwRunSprintRecords = new ArrayList<>();
                                    for (HsmwUserDriver hsmwUserDriver : hsmwUserDrivers) {

                                    HsmwDriverUser driverUser = hsmwDriverUserService.getById(hsmwUserDriver.getUserId());
                                    if (StringUtils.isNotBlank(driverUser.getName())) {
                                        userName += driverUser.getName() + "、";
                                    }
                                    HsmwRunSprintRecord hsmwRunSprintRecord = new HsmwRunSprintRecord();
                                    hsmwRunSprintRecord.setOrderId(orderCancelVO.getOrderId());
                                    hsmwRunSprintRecord.setRequestId(relation.getOrderVehicleRequestId());
                                    hsmwRunSprintRecord.setRelationId(relation.getId());
                                    hsmwRunSprintRecord.setFlag("1");
                                    hsmwRunSprintRecord.setDriverId(hsmwUserDriver.getId());
                                    hsmwRunSprintRecords.add(hsmwRunSprintRecord);

                                        WebSocketReturnVO vo = new WebSocketReturnVO();
                                        vo.setStatus(WebsocketTypeEnum.CANCEL_ORDER.getValue());
                                        vo.setMessage("您的订单已被取消，系统为您判断成为空跑订单。");
                                        String returnJson = JSONObject.toJSON(vo).toString();
                                        webSocket.AppointSending(driverUser.getUsername(), returnJson);
                                    }
                                    hsmwRunSprintRecordService.saveBatch(hsmwRunSprintRecords);

                                    HsmwLeasingCompany leasingCompany = hsmwLeasingCompanyService.getById(hsmwUserDrivers.get(0).getOwnCompanyId());
                                    if(StringUtils.isNotNull(leasingCompany)){
                                        hsmwOrderBalance.setRunSubsidy(leasingCompany.getSubsidyAmount());
                                        hsmwOrderBalance.setMovePumpSubsidy(leasingCompany.getMovePumpSubsidy());
                                    }
                                    List<HsmwConstructionPosition> positions = hsmwConstructionPositionService.list(new LambdaQueryWrapper<HsmwConstructionPosition>().eq(HsmwConstructionPosition::getOrderId, orderCancelVO.getOrderId()));
                                    String positionName = "";
                                    if(CollectionUtil.isNotEmpty(positions)){
                                        for (HsmwConstructionPosition position : positions) {
                                            if(StringUtils.isNotBlank(position.getPosition())){
                                                positionName += position.getPosition()+",";
                                            }
                                        }
                                    }
                                    hsmwOrderBalance.setDriverName(userName.substring(0,userName.length()-1));
                                    String vehicleId = hsmwUserDrivers.get(0).getVehicleId();
                                    HsmwVehicle hsmwVehicle = hsmwVehicleService.getById(vehicleId);
                                    hsmwOrderBalance.setCarNum(hsmwVehicle.getCarNum());
                                    hsmwOrderBalance.setVehicleType(hsmwVehicle.getVehicleType());
                                    hsmwOrderBalance.setConstructionUnitName(order.getConstructionUnitName());
                                    hsmwOrderBalance.setConstructionPosition(positionName.substring(0,positionName.length()-1));
                                    hsmwOrderBalance.setItemId(order.getItemId());
                                    hsmwOrderBalance.setItemName(order.getItemName());
                                    hsmwOrderBalance.setStatementsTime(LocalDateTime.now());
                                    hsmwOrderBalance.setOrderId(order.getId());
                                    hsmwOrderBalance.setRunCount("1");

                                    String concreteNum = hsmwConcreteInfoMapper.findConcreteNumByPosionId(order.getId());
                                    if (concreteNum != null && StringUtils.isNotBlank(concreteNum)) {
                                        hsmwOrderBalance.setConcreteNum(concreteNum);
                                    }
                                    hsmwOrderBalance.setRelationId(relation.getId());
                                    hsmwOrderBalance.setVehicleId(relation.getVehicleId());
                                    hsmwOrderBalance.setDriverId(hsmwUserDrivers.get(0).getId());
                                    hsmwOrderBalance.setConstructionTime(order.getCreateTime().toLocalDate());
                                    hsmwOrderBalance.setOrderStatus(relation.getOrderStatus());
                                    hsmwOrderBalance.setVehicleNum(relation.getVehicleNum());
                                    hsmwOrderBalanceMapper.insert(hsmwOrderBalance);
                                }
                                relation.setCancelOrderFlag("1");
                                relation.setCancelOrderTime(LocalDateTime.now());
                                relation.setOrderStatus(ChildOrderStatusEnum.CANCELED.getValue());
                            }
                            HsmwVehicle hsmwVehicle = hsmwVehicleService.getVehicleById(relation.getVehicleId());
                            List<HsmwUserDriver> drivers=  hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>()
                                    .eq(HsmwUserDriver::getVehicleId,relation.getVehicleId())
                                    .eq(HsmwUserDriver::getWorkStatus,CommonConstants.DRIVER_WORK));
                            List<HsmwDriverCancelOrderRecord> driverCancelOrderRecords = new ArrayList<>();
                            for(HsmwUserDriver driver :drivers){
                                HsmwDriverUser driverUser =hsmwDriverUserService.getById(driver.getUserId());
                                HsmwDriverCancelOrderRecord record = new HsmwDriverCancelOrderRecord();
                                record.setDriverId(driver.getId());
                                record.setDriverName(driverUser.getName());
                                record.setRequestId(request.getId());
                                record.setVehicleId(driver.getVehicleId());
                                record.setRelationId(relation.getId());
                                record.setOrderId(request.getOrderId());
                                record.setOrderStatus(record.getOrderStatus());
                                //2.2 添加的几个字段
                                record.setScore(driver.getScore());
                                record.setDriverUserId(driver.getUserId());
                                record.setYears(hsmwVehicle.getYears());
                                record.setArmSegment(hsmwVehicle.getArmSegment());
                                record.setVehicleBrand(hsmwVehicle.getVehicleBrand());
                                record.setAxis(hsmwVehicle.getAxis());
                                record.setVehicleLeftImage(hsmwVehicle.getVehicleLeftImage());
                                record.setVehicleRightImage(hsmwVehicle.getVehicleRightImage());
                                record.setDriverUserId(driver.getUserId());
                                record.setChassisBrand(hsmwVehicle.getChassisBrand());
                                record.setTrafficRate(hsmwVehicle.getTrafficRate());

                                hsmwDriverCancelOrderRecordMapper.insert(record);
                                //工长取消成功， 就会往系统消息中插入一条数据
                                HsmwDriverNews newss = new HsmwDriverNews();
                                if (relation.getOrderStatus().equals(ChildOrderStatusEnum.CANCELED.getValue())){
                                    msg = "您的订单已经被取消！";
                                    SendSmsUtil.sendDriverSmsCode(appId, appKey, "",driverOrderUnArrivedCanceled, smsSign, driverUser.getUsername());
                                    driver.setWorkStatus(CommonConstants.DRIVER_ACCEPT_ORDER);
                                    HsmwVehicle vehicle =hsmwVehicleService.getVehicleById(driver.getVehicleId());
                                    vehicle.setId(driver.getVehicleId());
                                    vehicle.setWorkStatus(CommonConstants.VEHICLE_FREE);
                                    hsmwVehicleService.updateById(vehicle);
                                }else {
                                    msg = "您的订单已被取消，请及时填写方量信息，以免遗漏";
                                    SendSmsUtil.sendDriverSmsCode(appId, appKey, "",driverOrderCanceled, smsSign, driverUser.getUsername());
                                }
                                newss.setMessage(msg);
                                newss.setUserId(driver.getUserId());
                                newss.setAlreadyRead("0");
                                news.add(newss);
                                //对APP进行离线推送
                                HsmwDriverUser user  = hsmwDriverUserService.getById(driver.getUserId());
                                String phoneNum = user.getUsername();
                                TencentPushUtils.pushMsg(msg,phoneNum,"");

                                String ids = driver.getId();
                                HsmwBanDriver banDriver = hsmwBanDriverService.getOne(new LambdaQueryWrapper<HsmwBanDriver>().eq(HsmwBanDriver::getDriverId, ids).eq(HsmwBanDriver::getStatus, "0"));
                                if (banDriver == null) {
                                    driver.setWorkStatus(CommonConstants.DRIVER_ACCEPT_ORDER);
                                } else {
                                    driver.setWorkStatus(CommonConstants.BAN_WORK);
                                    HsmwScoringRecord scoringRecord = new HsmwScoringRecord();
                                    scoringRecord.setDriverId(driver.getId());
                                    scoringRecord.setInitialScore(driver.getScore());
                                    scoringRecord.setEndScore(String.valueOf(Long.parseLong(driver.getScore()) - Long.parseLong(banDriver.getDeductPoints())));
                                    scoringRecord.setFluctuateScore("-"+banDriver.getDeductPoints());
                                    scoringRecord.setRemark("封禁扣除评分");
                                    hsmwScoringRecordMapper.insert(scoringRecord);
                                    driver.setScore(String.valueOf(Long.parseLong(driver.getScore()) - Long.parseLong(banDriver.getDeductPoints())));
                                    banDriver.setStatus("1");
                                    hsmwBanDriverService.updateById(banDriver);
                                }
                                hsmwUserDriverService.updateById(driver);

                            }
                            if(CollectionUtil.isNotEmpty(driverCancelOrderRecords)){

                            }
                            hsmwOrderVehicleRelationService.updateById(relation);
                            HsmwOrderVehicleRequest hsmwOrderVehicleRequest =  new HsmwOrderVehicleRequest();
                            hsmwOrderVehicleRequest.setId(relation.getOrderVehicleRequestId());
                            hsmwOrderVehicleRequest.setRequestStatus(RequestStatusEnum.CANCELED.getValue());
                            hsmwOrderVehicleRequest.setOperUserId(usernow.getId());
                            hsmwOrderVehicleRequest.setOperType(CancleTypeEnum.FOREMAN_CANCLE.getValue());
                            hsmwOrderVehicleRequest.setOperTime(LocalDateTime.now());
                            hsmwOrderVehicleRequestService.updateById(hsmwOrderVehicleRequest);
                            destoryGroup(relation.getId());
                        }else{
                            request.setRequestStatus(RequestStatusEnum.CANCELED.getValue());
                            request.setOperUserId(usernow.getId());
                            request.setOperType(CommonConstants.YES);
                            request.setOperTime(LocalDateTime.now());
                            hsmwOrderVehicleRequestService.updateById(request);
                        }
                    }else {
                        HsmwOrder order = hsmwOrderService.getHsmwOrderById(request.getOrderId());
                        request.setConcreteOrderStatus(ConcreteOrderStatusEnum.CANCELED.getValue());
                        //搅拌站取消的话 将 取消类型设置为 1
                        request.setOperType(CancleTypeEnum.FOREMAN_CANCLE.getValue());
                        request.setOperTime(LocalDateTime.now());
                        request.setEndTime(LocalDateTime.now());
                        boolean atc = hsmwOrderVehicleRequestService.updateById(request);
                        HsmwHtnUser user = hsmwHtnUserService.getById(request.getCreateUser());
                        if(atc){
                            String msg = "您的混凝土订单已被取消";
                            //给工长推送信息 搅拌站拒绝订单 的信息
                            HsmwHtnUser  hsmwUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
                            if(HtnUserTypeEnum.FOREMAN.getValue().equals(hsmwUser.getType()) || HtnUserTypeEnum.COMPANY.getValue().equals(hsmwUser.getType())  ||  ( HtnUserTypeEnum.CONCRETE.getValue().equals(hsmwUser.getType()) && !hsmwUser.getOwnCompanyId().equals(request.getConcretePlantId()) )){
                                HsmwConcretePlantInfo plantInfo = hsmwConcretePlantInfoMapper.selectById(request.getConcretePlantId());
                                //给搅拌站负责人 推送 下单人取消混凝土订单的信息
                                HsmwHtnUser concreteUser = hsmwHtnUserService.getHsmwUserById(plantInfo.getUserId());
                                if(StringUtils.isNotNull(concreteUser)){
                                    TencentPushUtils.pushForeManMsg(msg,concreteUser.getUsername(),"");
                                    //新增系统消息
                                    HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                                    hsmwDriverNews.setUserId(concreteUser.getId());
                                    hsmwDriverNews.setMessage(msg);
                                    hsmwDriverNews.setAlreadyRead("0");
                                    hsmwDriverNewsService.save(hsmwDriverNews);
                                }
                           /*     //发送混凝土订单的云打印
                                YLYNewOrderDTO newOrderDTO = new YLYNewOrderDTO();
                                newOrderDTO.setMechineId(plantInfo.getMechineId());
                                newOrderDTO.setItemName(order.getItemName());
                                newOrderDTO.setOrderId(order.getId());
                                newOrderDTO.setConstructionUnitName(order.getConstructionUnitName());
                                newOrderDTO.setItemPosition(order.getItemPosition());
                                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
                                newOrderDTO.setReachTime(dtf.format(request.getReachTime()));
                                newOrderDTO.setForemanName(order.getLinkmanName());
                                newOrderDTO.setForemanTel(order.getLinkmanTelephone());
                                newOrderDTO.setOperType(OperTypeEnum.CANCEL.getValue());
                                YLWUtils.sendCancelOrder(newOrderDTO);*/
                            }
                        }
                    }
                }
            }
            if (StringUtils.isListNotNull(news)){
                hsmwDriverNewsService.saveBatch(news);
            }
         /**/
            HsmwForcemanMedal hsmwForcemanMedal = hsmwForcemanMedalMapper.selectOne(new LambdaQueryWrapper<HsmwForcemanMedal>().eq(HsmwForcemanMedal::getUserId, usernow.getId()));
            if (null != hsmwForcemanMedal) {
                hsmwForcemanMedal.setCancellationOrder(hsmwForcemanMedal.getCancellationOrder() + 1L);
                hsmwForcemanMedalMapper.updateById(hsmwForcemanMedal);
            }else {
                HsmwForcemanMedal forcemanMedal = new HsmwForcemanMedal();
                forcemanMedal.setCancellationOrder(1L);
                forcemanMedal.setUserId(usernow.getId());
                hsmwForcemanMedalMapper.insert(forcemanMedal);
            }
            return new DataResponse("成功");
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"取消订单失败，请联系管理员！");
        }



    }

    public HtnPumpOrderDetailVo selectConcreteOrderDetail(String requestId) {
        HtnPumpOrderDetailVo htnOrderInfoVO = hsmwOrderMapper.selectConcreteOrderDetail(requestId);
        HashMap params = new HashMap();
        params.put("orderId",htnOrderInfoVO.getOrderId());
        List<HsmwConstructionPosition > ps= hsmwOrderMapper.selectPositionsByOrderId(params);
        htnOrderInfoVO.setHsmwConstructionPositionList(ps);

        //查询有混凝土记录那么 直接查询如果 没有记录 就查询记录并 查询出来
        List<HsmwConcreteOperate> hsmwConcreteOperates = null;
        List<HsmwConcreteOperate> concreteOperates = hsmwConcreteOperateService.list(new LambdaQueryWrapper<HsmwConcreteOperate>()
                .eq(HsmwConcreteOperate::getOrderId, htnOrderInfoVO.getOrderId()));
        if (CollectionUtil.isEmpty(concreteOperates)) {
            //查询出全部的混凝土的标号的类型
            List<HsmwConcreteInfo> hsmwConcreteInfoList = hsmwConcreteInfoMapper.selectConcretelist(params);
            hsmwConcreteInfoList.stream().forEach(hsmwConcreteInfo -> {
                HsmwConcreteOperate operate = new HsmwConcreteOperate();
                operate.setOrderId(htnOrderInfoVO.getOrderId());
                operate.setConcreteNum(hsmwConcreteInfo.getConcreteNum());
                operate.setExpectVolume(hsmwConcreteInfo.getExpectVolume());
                operate.setSlump(hsmwConcreteInfo.getSlump());
                operate.setIncreaseandOrDecrease(hsmwConcreteInfo.getIncreaseandOrDecrease());
                // operate.setOperUser(hsmwUser.getId());
                hsmwConcreteOperateMapper.insert(operate);
            });
            hsmwConcreteOperates = hsmwConcreteOperateMapper.selectList(new LambdaQueryWrapper<HsmwConcreteOperate>()
                    .eq(HsmwConcreteOperate::getOrderId, htnOrderInfoVO.getOrderId()));
        } else {
            hsmwConcreteOperates = concreteOperates;
        }
        htnOrderInfoVO.setHsmwConcreteOperates(hsmwConcreteOperates);

        return  htnOrderInfoVO;
    }

    public boolean updateOrderWorkStatusById(String id) {

        boolean suc = hsmwOrderMapper.updateOrderWorkStatusById(id);
        return suc;
    }



    public DataResponse findIdleVehicleCountAndDistance(String requestId) {
        HsmwOrderVehicleRequest request = hsmwOrderVehicleRequestMapper.selectById(requestId);
        request.setFlag(true);
        java. time.Duration duration = java.time.Duration.between(LocalDateTime.now(),  request.getReachTime());
        HsmwOrder order = hsmwOrderService.getHsmwOrderById(request.getOrderId());
        List<VehicleStatisticsVO> resList = new ArrayList<>();
        List<HsmwVehicle> resVehicleList = new ArrayList<>();
        //自营车辆的司机列表
        List<HsmwVehicle> selfrunVehicles = new ArrayList<>();
        //合作公司的司机列表
        List<HsmwVehicle> corperateVehicles = new ArrayList<>();
        //平台的其他的公司的司机列表
        List<HsmwVehicle> platformVehicles = new ArrayList<>();

        HsmwHtnUser createUser = hsmwHtnUserMapper.selectById(order.getCreateUser());
        //如果是公司用户 那么直接查询本公司的车辆作为自营车辆
        String selfrunCompanyId ="";
        if(HtnUserTypeEnum.COMPANY.getValue().equals(createUser.getType())){
            selfrunCompanyId= createUser.getOwnCompanyId();
        }
        //如果是搅拌站用户  则查询自营合作公司的Id
        if(HtnUserTypeEnum.CONCRETE.getValue().equals(createUser.getType())){
            List<HsmwCorporationCompany> corporationCompanies = hsmwCorporationCompanyMapper.selectList(new LambdaQueryWrapper<HsmwCorporationCompany>()
                    .eq(HsmwCorporationCompany::getConcretePlantId,createUser.getOwnCompanyId())
                    .eq(HsmwCorporationCompany::getCorperateType, CorperateTypeEnum.SELFRUN.getValue()));
            if(CollectionUtil.isNotEmpty(corporationCompanies)){
                selfrunCompanyId= corporationCompanies.get(0).getCorperateCompanyId();
            }
        }
        //如果下单人员是 工长或者项目的负责人
        //查询该项目绑定的泵送公司
        String itemCreateUserCompanyId=null;
        HsmwHtnUser itemCreator =null;
        if(HtnUserTypeEnum.FOREMAN.getValue().equals(createUser.getType())){
            HsmwItem item = hsmwItemService.getHsmwItemById(order.getItemId());
            itemCreator = hsmwHtnUserService.getHsmwUserById(item.getCreateUser());
            itemCreateUserCompanyId=itemCreator.getOwnCompanyId();
            if(StringUtils.isNotNull(itemCreator)){
                if(HtnUserTypeEnum.COMPANY.getValue().equals(itemCreator.getType())){
                    selfrunCompanyId= itemCreator.getOwnCompanyId();
                }
                //如果是搅拌站用户  则查询自营合作公司的Id
                if(HtnUserTypeEnum.CONCRETE.getValue().equals(itemCreator.getType())){
                    List<HsmwCorporationCompany> corporationCompanies = hsmwCorporationCompanyMapper.selectList(
                            new LambdaQueryWrapper<HsmwCorporationCompany>()
                                    .eq(HsmwCorporationCompany::getConcretePlantId,itemCreator.getOwnCompanyId())
                                    .eq(HsmwCorporationCompany::getCorperateType, CorperateTypeEnum.SELFRUN.getValue()));
                    if(CollectionUtil.isNotEmpty(corporationCompanies)){
                        selfrunCompanyId= corporationCompanies.get(0).getCorperateCompanyId();
                    }
                }
            }
        }
        if(!CommonConstants.YES.equals(order.getIfSelfChoose())){
            //当指定车辆的ID不为空的时候
            if(StringUtils.isNotBlank(selfrunCompanyId)){
                request.setLeasingCompanyId(selfrunCompanyId);
                selfrunVehicles = hsmwOrderService.getIdleVehicleListByRequestId(request,"1",createUser,null,itemCreator);
                if(CollectionUtil.isNotEmpty(selfrunVehicles)){
                    resVehicleList.addAll(selfrunVehicles);
                }
            }
            //租赁公司和搅拌站查询合作的公司的车辆
            corperateVehicles = hsmwOrderService.getIdleVehicleListByRequestId(  request,"2",createUser,itemCreateUserCompanyId,itemCreator);
            if(CollectionUtil.isNotEmpty(corperateVehicles)){
                resVehicleList.addAll(corperateVehicles);
            }
        }else {
            platformVehicles = hsmwOrderService.getIdleVehicleListByRequestId(request,"4",createUser,itemCreateUserCompanyId,itemCreator);
            if(CollectionUtil.isNotEmpty(platformVehicles)){
                resVehicleList.addAll(platformVehicles);
            }
        }
        if(CollectionUtil.isNotEmpty(resVehicleList)){
            List<HsmwVehicle> list = resVehicleList;
            if (CollectionUtil.isNotEmpty(list)) {
                List<VehicleSelectVO> voList = vehicleGroup(list);
                Iterator<VehicleSelectVO> voIterator = voList.iterator();
                while(voIterator.hasNext()){
                    VehicleStatisticsVO vehicleStatisticsVO = new VehicleStatisticsVO();
                    VehicleSelectVO vehicleSelectVO= voIterator.next();
                    List<HsmwVehicle> vehicles =vehicleSelectVO.getVehicleList();
                    List<HsmwVehicle> temp=new ArrayList<>();
                    temp.addAll(vehicles);
                    List<Long> longList = new ArrayList();
                    Iterator<HsmwVehicle> it = vehicles.iterator();
                    while (it.hasNext()) {
                        HsmwVehicle hsmwVehicle = it.next();
                        String vehicleLocalteInfo = null;
                        String destinationLocateInfo = order.getLng() + "," + order.getLat();
                        if (StringUtils.isNotBlank(hsmwVehicle.getImeiNum()) || StringUtils.isNotBlank(hsmwVehicle.getIdentifyingCode())) {
                            GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(hsmwVehicle.getImeiNum(),hsmwVehicle.getFlag(),hsmwVehicle.getIdentifyingCode());
                            if (StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
                                vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                            }
                        }
                        HashMap calculateParam = new HashMap();
                        calculateParam.put("origin", vehicleLocalteInfo);
                        calculateParam.put("destination", destinationLocateInfo);
                        Map<String, Long> mapTimeAndDistance = GaoDeInfoUtils.calculateDistanceDistence(calculateParam);
                        Long time =0L;
                        if(StringUtils.isNotNull(mapTimeAndDistance.get("time"))) {
                            time  =mapTimeAndDistance.get("time") / 3600;
                        }
                        vehicleStatisticsVO.setTime(time);
                        vehicleStatisticsVO.setVehicleNum( list.size());
                        Long distence = 0L;
                        if(StringUtils.isNotNull(mapTimeAndDistance.get("distence"))){
                            distence= mapTimeAndDistance.get("distence") / 1000;
                        }
                        long sconds = duration.toMillis() / 1000;
                        longList.add(distence);
                        if ((float) sconds / 3600 < ((float) time / 3600)) {
                            temp.remove(hsmwVehicle);
                            continue;
                        }
                        System.err.println("距离--->" + distence);
                    }
                    if(CollectionUtil.isNotEmpty(temp)){
                        long min = longList.stream().mapToLong(lo -> lo.longValue()).min().orElse(0L);
                        vehicleStatisticsVO.setDistance(min);
                        vehicleStatisticsVO.setVehicleNum(temp.size());
                        vehicleStatisticsVO.setVehicleType(vehicleSelectVO.getVehicleType());
                        vehicleStatisticsVO.setVehicleModel(vehicleSelectVO.getVehicleModel());
                        resList.add(vehicleStatisticsVO);
                    }
                }
            }
        }
        return new DataResponse<>(CommonConstants.ResponseStatus.SUCCESS, resList);
    }

    private List<VehicleSelectVO> vehicleGroup(List<HsmwVehicle> list) {
        List<VehicleSelectVO> res = new ArrayList<>();
        for(HsmwVehicle vehicle :list){
            if(CollectionUtil.isEmpty(res)){
                VehicleSelectVO vo = new VehicleSelectVO();
                vo.setVehicleType(vehicle.getVehicleType());
                vo.setVehicleModel(vehicle.getVehicleModel());
                List<HsmwVehicle> vehicles = new ArrayList<>();
                vehicles.add(vehicle);
                vo.setVehicleList(vehicles);
                res.add(vo);
                continue;
            }
            boolean falg=false;
            List<VehicleSelectVO> temp =new ArrayList<>();
            temp.addAll(res);
            for(VehicleSelectVO vehicleSelectVO :res){
                if(vehicleSelectVO.getVehicleModel().equals(vehicle.getVehicleModel()) && vehicleSelectVO.getVehicleType().equals(vehicle.getVehicleType())){
                    List<HsmwVehicle> vehicles = vehicleSelectVO.getVehicleList();
                    temp.remove(vehicleSelectVO);
                    vehicles.add(vehicle);
                    vehicleSelectVO.setVehicleList(vehicles);
                    temp.add(vehicleSelectVO);
                    falg=true;
                    continue;
                }
            }
            res = temp;
            if(!falg){
                VehicleSelectVO vo = new VehicleSelectVO();
                vo.setVehicleType(vehicle.getVehicleType());
                vo.setVehicleModel(vehicle.getVehicleModel());
                List<HsmwVehicle> vehicles = new ArrayList<>();
                vehicles.add(vehicle);
                vo.setVehicleList(vehicles);
                res.add(vo);
            }
        }
        return  res;
    }

    public  VehicleSelectVO checkifContains(List<VehicleSelectVO> res ,HsmwVehicle vehicle){
        VehicleSelectVO resVO = null;
        if(CollectionUtil.isEmpty(res)){
            resVO =null;
        }
        for(VehicleSelectVO vo :res){
            if(vo.getVehicleType().equals(vehicle.getVehicleType()) && vo.getVehicleModel().equals(vehicle.getVehicleModel())){
                resVO = vo;
                break;
            }
        }
        return resVO;
    }


    public DataResponse replaceOtherVehicle(ReplaceVehicleVO vo) {
        HsmwOrderVehicleRequest request = hsmwOrderVehicleRequestMapper.selectById(vo.getRequestId());
        try {
            request.setVehicleModel(vo.getVehicleModel());
            request.setVersion(request.getVersion()+1);
            hsmwOrderVehicleRequestService.updateById(request);
            HsmwOrder hsmwOrder = hsmwOrderMapper.selectById(request.getOrderId());
            HsmwOrderVO hsmwOrderVO = new HsmwOrderVO();
            BeanUtil.copyProperties(hsmwOrder, hsmwOrderVO);
            hsmwOrderVO.setRequestId(vo.getRequestId());
            ReturnVO returnVO = hsmwOrderService.dispatchOrder(hsmwOrderVO);
            return  new DataResponse("更改成功");

        }catch (Exception e){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"替换车辆类型失败，请联系管理员！");
        }
    }

    @Value(value = "${tcloud.sdkappid}")
    private Long sdkappid;

    @Value(value = "${tcloud.sdkKey}")
    private String sdkKey;

    @Value(value = "${tcloud.admin}")
    private String admin;
    private static HashMap userSignHub =new HashMap<>();


    public   String  getAdminUserSign(){
        if(userSignHub.size()==0 || StringUtils.isNull(userSignHub.get("userSign"))){
            String userSign = com.hsmw.api.utils.TLSSigAPIv2.generateForemanToken(sdkappid,sdkKey,admin);
            userSignHub.put("createForeTime",new Date());
            userSignHub.put("userSign",userSign);
            return userSign;
        }else{
            Date createTime = (Date)userSignHub.get("createForeTime");
            Long now  = System.currentTimeMillis();
            if(now - createTime.getTime() >= 3600*24*360){
                //如果创建时间大于7200s 则过期了，需要重新生成
                String userSign = com.hsmw.api.utils.TLSSigAPIv2.generateForemanToken(sdkappid,sdkKey,admin);
                userSignHub.put("createForeTime",new Date());
                userSignHub.put("userSign",userSign);
                return  userSign;
            }else{
                return  (String) userSignHub.get("userSign");
            }
        }
    }



    public void   destoryGroup(String relationID){
        StringBuilder reqUrl = new StringBuilder("https://console.tim.qq.com/v4/group_open_http_svc/destroy_group");//"?&identifier=administrator&&random=999999&contenttype=
        if(StringUtils.isNotNull(sdkappid)){
            reqUrl.append("?").append("sdkappid=").append(sdkappid);
        }
        if(StringUtils.isNotNull(admin)){
            reqUrl.append("&").append("identifier=").append(admin);
        }
        String userSign= getAdminUserSign();
        reqUrl.append("&").append("usersig=").append(userSign);
        int max=1000000,min=1;
        int random = (int) (Math.random()*(max-min)+min);
        reqUrl.append("&").append("random=").append(random);
        reqUrl.append("&").append("contenttype=").append("json");

        JSONObject param = new JSONObject();
        param.put("GroupId",relationID);
        String res = "";
        try {
            res = HttpAPIUtils.doPost(reqUrl.toString(),param);
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println(res);
      /*  if(StringUtils.isNotBlank(res)){
            JSONObject result = JSON.parseObject(res);
            String
        }
        */
    }

    public  void   removeAccount(String userId){
        StringBuilder reqUrl = new StringBuilder("https://console.tim.qq.com/v4/im_open_login_svc/account_delete");//"?&identifier=administrator&&random=999999&contenttype=
        //https://console.tim.qq.com/v4/im_open_login_svc/account_delete?sdkappid=88888888&identifier=admin&usersig=xxx&random=99999999&contenttype=json
        if(StringUtils.isNotNull(sdkappid)){
            reqUrl.append("?").append("sdkappid=").append(sdkappid);
        }
        if(StringUtils.isNotNull(admin)){
            reqUrl.append("&").append("identifier=").append(admin);
        }
        String userSign= getAdminUserSign();
        reqUrl.append("&").append("usersig=").append(userSign);
        int max=1000000,min=1;
        int random = (int) (Math.random()*(max-min)+min);
        reqUrl.append("&").append("random=").append(random);
        reqUrl.append("&").append("contenttype=").append("json");

        JSONObject param = new JSONObject();
        JSONArray array=new JSONArray();
        JSONObject par = new JSONObject();
        par.put("UserID",userId);
        array.add(par);
        param.put("DeleteItem",array);
        String res = "";
        try {
            res = HttpAPIUtils.doPost(reqUrl.toString(),param);
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println(res);
      /*  if(StringUtils.isNotBlank(res)){
            JSONObject result = JSON.parseObject(res);
            String
        }
        */
    }

}
